JSON (JavaScript Object Notation) is a light-weight, human-readable, and language-independent data exchange format. Originally derived from JavaScript in the early 2000s, JSON has quickly become a de-facto standard format for exchanging data between the servers and the clients.

JSON has only two data structures: objects and arrays. An object is an unordered set of zero or more key-value pairs. An array is a list of zero or more values. The values can be strings, numbers, booleans, null, nested objects, and arrays.

Almost all programming languages including Java, Python, Node.js, JavaScript, and Ruby provide code to generate and parse the JSON data. In this article, you'll learn how to read and write JSON in Java.

Let us create a simple JSON file which contains a single object that describes a customer, as shown below:

customer.json

{
  "id": 1,
  "name": "John Doe",
  "email": "john.doe@example.com",
  "age": 32,
  "address": {
    "street": "155 Middleville Road",
    "city": "New York",
    "state": "New York",
    "zipCode": 10045
  },
  "paymentMethods": [
    "PayPal",
    "Stripe"
  ],
  "projects": [
    {
      "title": "Business Website",
      "budget": 45000
    },
    {
      "title": "Sales Dashboard",
      "budget": 85000
    }
  ]
}

Unfortunately, Java does not provide any native library for processing JSON. In this article, we will look at some of the best open-source libraries available for generating and parsing JSON in Java.

1. JSON.simple

JSON.simple is a simple Java library for processing JSON in Java. It allows you to read, write, parse, and query JSON in full compliance with JSON specifications (RFC4627).

To add JSON.simple to your Gradle project, add the following dependency to build.gradle file:

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

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

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

Write JSON to a File using JSON.simple

Here is an example that demonstrates how to use JSON.simple library to write JSON data to a file:

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

    // create customer object
    JsonObject customer = new JsonObject();
    customer.put("id", 1);
    customer.put("name", "John Doe");
    customer.put("email", "john.doe@example.comDoe");
    customer.put("age", 32);

    // create address object
    JsonObject address = new JsonObject();
    address.put("street", "155 Middleville Road");
    address.put("city", "New York");
    address.put("state", "New York");
    address.put("zipCode", 10045);

    // add address to customer
    customer.put("address", address);

    // add customer payment methods
    JsonArray pm = new JsonArray();
    pm.addAll(Arrays.asList("PayPal", "Stripe"));
    customer.put("paymentMethods", pm);

    // create projects
    JsonArray projects = new JsonArray();

    // create 1st project
    JsonObject p1 = new JsonObject();
    p1.put("title", "Business Website");
    p1.put("budget", 4500);

    // create 2nd project
    JsonObject p2 = new JsonObject();
    p2.put("title", "Sales Dashboard");
    p2.put("budget", 8500);

    // add projects
    projects.addAll(Arrays.asList(p1, p2));

    // add projects to customer
    customer.put("projects", projects);

    // write JSON to file
    Jsoner.serialize(customer, writer);

    //close the writer
    writer.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

As you can see above, we are using the JsonObject and JsonArray classes to generating a customer object with personal details, projects, payment methods, and more. The JsonObject class is used to create a JSON object with unordered key-value pairs. The JsonArray class is used to create a JSON array with multiple objects.

Read JSON from a File using JSON.simple

Let us now read JSON from the file we just created above. JSON.simple provides the Jsoner.deserialize() static method for parsing a JSON file. Here is an example:

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

    // create parser
    JsonObject parser = (JsonObject) Jsoner.deserialize(reader);

    // read customer details
    BigDecimal id = (BigDecimal) parser.get("id");
    String name = (String) parser.get("name");
    String email = (String) parser.get("email");
    BigDecimal age = (BigDecimal) parser.get("age");

    System.out.println(id);
    System.out.println(name);
    System.out.println(email);
    System.out.println(age);

    // read address
    Map<Object, Object> address = (Map<Object, Object>) parser.get("address");
    address.forEach((key, value) -> System.out.println(key + ": " + value));

    // read payment method
    JsonArray paymentMethods = (JsonArray) parser.get("paymentMethods");
    paymentMethods.forEach(System.out::println);

    // read projects
    JsonArray projects = (JsonArray) parser.get("projects");
    projects.forEach(entry -> {
        JsonObject project = (JsonObject) entry;
        System.out.println(project.get("title"));
        System.out.println(project.get("budget"));
    });

    //close reader
    reader.close();

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

In the above example, we are creating a JsonObject object by explicitly casting the object returned by the Jsoner.deserialize() method. We then read the JSON objects one-by-one by casting them to their actual data type.

For more JSON.simple examples, check out How to read and write JSON using JSON.simple in Java tutorial.

2. Jackson

Jackson is another popular Java library for reading and writing JSON data. Jackson provides the ObjectMapper class to convert Java Objects into their JSON representation. It can also be used to convert a JSON object back to an equivalent Java object.

Just add the following dependency to your Gradle project's build.gradle file to include the Jackson support:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.0'

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

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</version>
</dependency>

Note: If you are looking to parse JSON data in Spring Boot, check out the Processing JSON Data in Spring Boot guide.

Write JSON to a File using Jackson

ObjectMapper provides the writeValue() method to convert a Java object to a JSON string. The following example shows how to use the Jackson library to write JSON data to a file:

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

    // create a map for customer properties
    Map<String, Object> customer = new HashMap<>();
    customer.put("id", 1);
    customer.put("name", "John Doe");
    customer.put("email", "john.doe@example.com");
    customer.put("age", 32);

    // create address
    Map<String, Object> address = new HashMap<>();
    address.put("street", "155 Middleville Road");
    address.put("city", "New York");
    address.put("state", "New York");
    address.put("zipCode", 10045);

    // add address to customer
    customer.put("address", address);

    // create payment methods
    customer.put("paymentMethods", Arrays.asList("PayPal", "Stripe"));

    // create 1st project
    Map<String, Object> p1 = new HashMap<>();
    p1.put("title", "Business Website");
    p1.put("budget", 4500);

    // create 2nd project
    Map<String, Object> p2 = new HashMap<>();
    p2.put("title", "Sales Dashboard");
    p2.put("budget", 8500);

    // add projects to customer
    customer.put("projects", Arrays.asList(p1, p2));

    // create ObjectMapper instance
    ObjectMapper mapper = new ObjectMapper();

    // write JSON to file
    writer.write(mapper.writeValueAsString(customer));

    //close the writer
    writer.close();
} catch (Exception ex) {
    ex.printStackTrace();
}

As you can see above, we are using the writeValueAsString() method to serialize a map object to a JSON string. The generated JSON string is then written to the file.

Read JSON from a File Using Jackson

Reading JSON from a file using Jackson is easier than the JSON.simple library. The ObjectMapper class can also be used to construct a hierarchical tree of nodes from JSON data. In the JSON tree model, you can access a specific node and read its value. In the tree model, each node is of type JsonNode which provides different methods to work with specific keys.

Here is an example that parses the customer.json file by using the Jackson library:

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

    //create ObjectMapper instance
    ObjectMapper objectMapper = new ObjectMapper();

    //read customer.json file into tree model
    JsonNode parser = objectMapper.readTree(reader);

    // read customer details
    System.out.println(parser.path("id").asLong());
    System.out.println(parser.path("name").asText());
    System.out.println(parser.path("email").asText());
    System.out.println(parser.path("age").asLong());

    // read address
    JsonNode address = parser.path("address");
    System.out.println(address.path("street").asText());
    System.out.println(address.path("city").asText());
    System.out.println(address.path("state").asText());
    System.out.println(address.path("zipCode").asLong());

    // read payment method
    for (JsonNode pm : parser.path("paymentMethods")) {
        System.out.println(pm.asText());
    }

    // read projects
    for (JsonNode project : parser.path("projects")) {
        System.out.println(project.path("title").asText());
        System.out.println(project.path("budget").asLong());
    }

    //close reader
    reader.close();

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

3. Gson

Gson is yet another Java library, developed and maintained by Google, for converting Java Objects into their JSON representation. You can also use it to convert a JSON string back to an equivalent Java object.

Gson provides simple toJson() and fromJson() methods that you can use to easily convert a Java object to and from JSON.

To add Gson to your Gradle project, add the below dependency to the build.gralde file:

implementation 'com.google.code.gson:gson:2.8.6'

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

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>

Write JSON to a File using Gson

The following example demonstrates how to use the toJson() method to convert a Java collection to a JSON string and then write it to a file:

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

    // create a map for customer properties
    Map<String, Object> customer = new HashMap<>();
    customer.put("id", 1);
    customer.put("name", "John Doe");
    customer.put("email", "john.doe@example.com");
    customer.put("age", 32);

    // create address
    Map<String, Object> address = new HashMap<>();
    address.put("street", "155 Middleville Road");
    address.put("city", "New York");
    address.put("state", "New York");
    address.put("zipCode", 10045);

    // add address to customer
    customer.put("address", address);

    // create payment methods
    customer.put("paymentMethods", Arrays.asList("PayPal", "Stripe"));

    // create 1st project
    Map<String, Object> p1 = new HashMap<>();
    p1.put("title", "Business Website");
    p1.put("budget", 4500);

    // create 2nd project
    Map<String, Object> p2 = new HashMap<>();
    p2.put("title", "Sales Dashboard");
    p2.put("budget", 8500);

    // add projects to customer
    customer.put("projects", Arrays.asList(p1, p2));

    // create Gson instance
    Gson gson = new Gson();

    // write JSON to file
    writer.write(gson.toJson(customer));

    //close the writer
    writer.close();

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

The above code looks very much similar to Jackson's code for writing JSON to a file. The only difference is we are now using the toJson() method from the Gson class for converting the collection to a JSON string.

Read JSON from a File using Gson

We can use the JsonParser class that comes with the Gson library to parse the JSON file we just created. Here is an example:

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

    //create JsonObject instance
    JsonObject parser = JsonParser.parseReader(reader).getAsJsonObject();

    // read customer details
    System.out.println(parser.get("id").getAsLong());
    System.out.println(parser.get("name").getAsString());
    System.out.println(parser.get("email").getAsString());
    System.out.println(parser.get("age").getAsLong());

    // read address
    JsonObject address = parser.get("address").getAsJsonObject();
    System.out.println(address.get("street").getAsString());
    System.out.println(address.get("city").getAsString());
    System.out.println(address.get("state").getAsString());
    System.out.println(address.get("zipCode").getAsLong());

    // read payment method
    for (JsonElement pm : parser.get("paymentMethods").getAsJsonArray()) {
        System.out.println(pm.getAsString());
    }

    // read projects
    for (JsonElement project : parser.get("projects").getAsJsonArray()) {
        JsonObject obj = project.getAsJsonObject();
        System.out.println(obj.get("title").getAsString());
        System.out.println(obj.get("budget").getAsLong());
    }

    //close reader
    reader.close();

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

4. Moshi

Moshi is another powerful JSON library created by Square for Kotlin and Java. It makes it easy to parse JSON into Java objects as well as convert Java Objects into their JSON representation. Moshi has built-in support for reading and writing Java's core data types including primitives, collections, strings, and enums.

If you want to use Moshi in a Gradle project, include the following dependency to your build.gradle file:

implementation 'com.squareup.moshi:moshi:1.8.0'

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

<dependency>
  <groupId>com.squareup.moshi</groupId>
  <artifactId>moshi</artifactId>
  <version>1.8.0</version>
</dependency>

Write JSON to a File using Moshi

Moshi provides the JsonWriter class that can be used to write a JSON encoded value to a stream, one token at a time, as shown below:

try {
    // create a JSON writer
    JsonWriter writer = JsonWriter.of(Okio.buffer(Okio.sink(Paths.get("customer.json").toFile())));

    // create top-level object
    writer.beginObject();

    writer.name("id").value(1);
    writer.name("name").value("John Doe");
    writer.name("email").value("john.doe@example.com");
    writer.name("age").value(32);

    // create address object
    writer.name("address");
    writer.beginObject();
    writer.name("street").value("155 Middleville Road");
    writer.name("city").value("New York");
    writer.name("state").value("New York");
    writer.name("zipCode").value(10045);
    writer.endObject();

    // add customer payment methods
    writer.name("paymentMethods");
    writer.beginArray();
    writer.value("PayPal").value("Stripe");
    writer.endArray();

    // start projects array
    writer.name("projects");
    writer.beginArray();

    // create 1st project
    writer.beginObject();
    writer.name("title").value("Business Website");
    writer.name("budget").value(4500);
    writer.endObject();

    // create 2nd project
    writer.beginObject();
    writer.name("title").value("Sales Dashboard");
    writer.name("budget").value(8500);
    writer.endObject();

    // close projects array
    writer.endArray();

    // close top-level object
    writer.endObject();

    //close the writer
    writer.close();

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

As you can see above, we have created an instance of JsonWriter to encode our data as JSON. We then called different methods on the write object to create a JSON object with nested objects and arrays.

Read JSON from a File using Moshi

Let us use the JsonReader class provided by Moshi to parse JSON from a file. It reads a JSON encode value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name-value pairs are represented by a single token.

Here is an example:

try {
    // create a JSON reader
    JsonReader reader = JsonReader.of(Okio.buffer(Okio.source(Paths.get("customer.json").toFile())));

    // start top-level object
    reader.beginObject();

    // read all tokens
    while (reader.hasNext()) {
        String name = reader.nextName();

        // read address
        if (name.equals("address")) {
            reader.beginObject();
            while (reader.hasNext()) {
                String key = reader.nextName();
                if (key.equals("zipCode")) {
                    System.out.println(reader.nextLong());
                } else {
                    System.out.println(reader.nextString());
                }
            }
            reader.endObject();
        }

        // read payment methods
        else if (name.equals("paymentMethods")) {
            reader.beginArray();
            while (reader.hasNext()) {
                System.out.println(reader.nextString());
            }
            reader.endArray();
        }

        // read projects
        else if (name.equals("projects")) {
            reader.beginArray();
            while (reader.hasNext()) {
                reader.beginObject();
                while (reader.hasNext()) {
                    String key = reader.nextName();
                    if (key.equals("title")) {
                        System.out.println(reader.nextString());
                    } else {
                        System.out.println(reader.nextLong());
                    }
                }
                reader.endObject();
            }
            reader.endArray();
        }

        // read other details
        else {
            System.out.println(reader.nextString());
        }
    }

    // close top-level object
    reader.endObject();

    //close the writer
    reader.close();

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

Conclusion

That's all folks for reading and writing JSON files in Java. There are no native libraries for efficiently processing JSON data in Java.

In this article, I have discussed four different open-source libraries for reading, writing, and parsing JSON data in Java. These libraries include JSON.simple, Jackson, Gson, and Moshi.

So what's the best JSON library? Personally, I use and recommend Jackson. It is a suite of data processing tools for Java that can be used to parse not only JSON but other data formats too like CSV, XML, YAML, and more.

Read Next: Processing JSON Data in Spring Boot

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.