# How to read and write JSON using JSON.simple in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Oct 27, 2019, updated Nov 15, 2019. Topics: Java, JSON.
Canonical URL: https://attacomsian.com/blog/json-simple-read-write-json

> A complete guide to learn how to read and write JSON to a file as well as convert a Java Object to JSON and back by using the JSON.simple library.

In [an earlier article](https://attacomsian.com/blog/java-read-write-json-files), I wrote about reading and writing JSON files in Java using different open-source libraries. In this article, I will focus on one of those libraries &mdash; [JSON.simple](https://code.google.com/archive/p/json-simple/) &mdash; to convert Java Objects into JSON and back.

JSON.simple is a lightweight Java library for processing JSON that can be used to read, write, and parse JSON. The produced JSON is fully complaint with JSON specification ([RFC4627](http://www.ietf.org/rfc/rfc4627.txt)).

## Dependencies

To add JSON.simple to your [Gradle](https://attacomsian.com/blog/install-gradle-on-ubuntu) project, add the following dependency to `build.gradle` file:

```groovy
implementation 'com.github.cliftonlabs:json-simple:3.1.0'
```

For Maven, include the below dependency to your `pom.xml` file:

```xml
<dependency>
    <groupId>com.github.cliftonlabs</groupId>
    <artifactId>json-simple</artifactId>
    <version>3.1.0</version>
</dependency>
```


## Create Java Class

Let us create a simple Java class named `Book` that we will use to convert Java Objects to JSON and back. JSON.simple requires this class to implement the `Jsonable` interface as well as override the `toJson()` method:

<p class="file-desc"><span>Book.java</span></p>

```java
package com.attacomsian;

import com.github.cliftonlabs.json_simple.JsonObject;
import com.github.cliftonlabs.json_simple.Jsonable;

import java.io.IOException;
import java.io.Writer;

public class Book implements Jsonable {

    private String title;
    private String isbn;
    private long year;
    private String[] authors;

    public Book() {
    }

    public Book(String title, String isbn, long year, String[] authors) {
        this.title = title;
        this.isbn = isbn;
        this.year = year;
        this.authors = authors;
    }

    // getters and setters, equals(), toString() .... (omitted for brevity)

    @Override
    public String toJson() {
        JsonObject json = new JsonObject();
        json.put("title", this.title);
        json.put("isbn", this.isbn);
        json.put("year", this.year);
        json.put("authors", this.authors);
        return json.toJson();
    }

    @Override
    public void toJson(Writer writable) throws IOException {
        try {
            writable.write(this.toJson());
        } catch (Exception ignored) {
        }
    }
}
```

## Convert Java Object to JSON

JSON.simple provides the `Jsoner` utility class for converting a Java object to a JSON string, as shown below:

```java
try {
    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[]{"Bruce Eckel"});

    // convert book object to JSON
    String json = Jsoner.serialize(book);

    // prettify JSON
    json = Jsoner.prettyPrint(json);

    // print JSON
    System.out.println(json);

} catch (Exception ex) {
    ex.printStackTrace();
}
```

The above example code should print the following on the console:

```json
{
    "year":1998,
    "isbn":"978-0131872486",
    "title":"Thinking in Java",
    "authors":[
        "Bruce Eckel"
    ]
}
```

You can even **write the converted JSON string directly to a file** using `Jsoner.serialize()`:

```java
try {
    // create a writer
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("book.json"));

    // create book object
    Book book = new Book("Thinking in Java", "978-0131872486", 1998,
            new String[] {"Bruce Eckel"});

    // convert book object to JSON and write to book.json
    Jsoner.serialize(book, writer);

    // close the writer
    writer.close();

} catch (Exception ex) {
    ex.printStackTrace();
}
```

The `book.json` file should include the following JSON string:

```json
{"year":1998,"isbn":"978-0131872486","title":"Thinking in Java","authors":["Bruce Eckel"]}
```

## Convert List of Java Objects to JSON Array

To convert a list of Java objects to a JSON array, all you need to do is just create a `List` of `Book` and pass it to `Jsoner.serialize()`, as shown below:

```java
try {
    // create a writer
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("books.json"));

    // create books list
    List<Book> books = Arrays.asList(
            new Book("Thinking in Java", "978-0131872486", 1998,
                    new String[]{"Bruce Eckel"}),
            new Book("Head First Java", "0596009208", 2003,
                    new String[]{"Kathy Sierra", "Bert Bates"})
    );

    // convert books list to JSON and write to books.json
    Jsoner.serialize(books, writer);

    // close the writer
    writer.close();

} catch (Exception ex) {
    ex.printStackTrace();
}
```

The `books.json` file should include the following JSON array:

```json
[
  {
    "year": 1998,
    "isbn": "978-0131872486",
    "title": "Thinking in Java",
    "authors": [
      "Bruce Eckel"
    ]
  },
  {
    "year": 2003,
    "isbn": "0596009208",
    "title": "Head First Java",
    "authors": [
      "Kathy Sierra",
      "Bert Bates"
    ]
  }
]
```

## Convert JSON to Java Object

Unfortunately, there is **no direct way to convert a JSON string to a Java Object** using JSON.simple. For this, we have to either use the 3rd-party library like [Dozer](https://github.com/DozerMapper/dozer) or manually build the object.

Let us use the Dozer library by adding the following dependency to your Gradle's project `build.gradle` file:

```groovy
implementation 'com.github.dozermapper:dozer-core:6.5.0'
```

For Maven, add the below dependency to your `pom.xml` file:

```xml
<dependency>
    <groupId>com.github.dozermapper</groupId>
    <artifactId>dozer-core</artifactId>
    <version>6.5.0</version>
</dependency>
```

The following example demonstrates how to read and parse JSON from a file into a Java Object:

```java
try {
    // create a reader
    Reader reader = Files.newBufferedReader(Paths.get("book.json"));

    // read JSON from a file
    JsonObject jsonObject = (JsonObject) Jsoner.deserialize(reader);

    // create a Dozer mapper
    Mapper mapper = DozerBeanMapperBuilder.buildDefault();

    // convert JsonObject to Book
    Book book = mapper.map(jsonObject, Book.class);

    // print the book
    System.out.println(book);

    // close the reader
    reader.close();

} catch (Exception ex) {
    ex.printStackTrace();
}
```

Now if you run the above code, you should see the following output printed on the console:

```bash
Book{title='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]}
```

## Convert JSON Array to List of Java Objects

To convert a JSON array to a list of Java Objects, we can use the above example code with a few modifications:

```java
try {
    // create a reader
    Reader reader = Files.newBufferedReader(Paths.get("books.json"));

    // read JSON from a file
    JsonArray objects = Jsoner.deserializeMany(reader);

    // create a Dozer mapper
    Mapper mapper = DozerBeanMapperBuilder.buildDefault();

    // convert JsonArray to List<Book>
    JsonArray jsonArray = (JsonArray) objects.get(0);
    List<Book> books = jsonArray.stream()
            .map(obj -> mapper.map(obj, Book.class))
            .collect(Collectors.toList());

    // print all books
    books.forEach(System.out::println);

    // close the reader
    reader.close();

} catch (Exception ex) {
    ex.printStackTrace();
}
```

The output should be something like the following:

```bash
Book{title='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]}
Book{title='Head First Java', isbn='0596009208', year=2003, authors=[Kathy Sierra, Bert Bates]}
```

## Conclusion

That's all folks. In this article, you have learned how to read and write JSON using the JSON.simple library in Java.

JSON.simple is no longer actively maintained and is only good for simple use cases. For better JSON serialization/deserialization, you should either use [Jackson](https://attacomsian.com/blog/jackson-read-write-json) or [Gson](https://attacomsian.com/blog/java-read-write-json-files#3-gson). Check out the [reading and writing JSON files in Java](https://attacomsian.com/blog/java-read-write-json-files) to learn more about all modern JSON libraries.
