json

Java JSON parser Example

In this post, we feature a comprehensive Java JSON parser Example. JSON is simply a text format that facilitates reading and writing. It is a widely used data-interchange language because of its parsing and its generation is easy for machines. In Java language, there are many ways for JSON processing.

1. JSON Parsers

In this section, we will see four different parsers for JSON available in the Java ecosystem.

1.1. Simple JSON parser

In this section we are going to use a common Java toolkit for JSONJSON.simple. Before start coding we have to set a proper environment for the compiler to recognize the JSON's classes. If you want to build your project via Maven, you should add the following dependency to your pom.xml:

pom.xml

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1</version>
</dependency>

As we mentioned, we will show how we can parse a JSON file, so we will make our own .json file. The file should be placed in src/main/resources directory. This file is named jsonTestFile.json and has the following structure:

jsonTestFile.json

{
  "id": 1,
  "firstname": "Katerina",
  "languages": [
    {
      "lang": "en",
      "knowledge": "proficient"
    },
    {
      "lang": "fr",
      "knowledge": "advanced"
    }
  ],
  "job": {
    "site": "www.javacodegeeks.com",
    "name": "Java Code Geeks"
  }
}

Now create a java file in your project, named JsonParseTest. Then paste the following code.

JsonParseTest.java

package com.javacodegeeks.javabasics.jsonparsertest;
 
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
 
public class JsonParseTest {
 
    private static final String filePath = "jsonTestFile.json";

    public static void main(String[] args) {

        try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) {
            // read the json file


            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

            // get a String from the JSON object
            String firstName = (String) jsonObject.get("firstname");
            System.out.println("The first name is: " + firstName);

            // get a number from the JSON object
            long id = (long) jsonObject.get("id");
            System.out.println("The id is: " + id);

            // get an array from the JSON object
            JSONArray lang = (JSONArray) jsonObject.get("languages");

            // take the elements of the json array
            for (int i = 0; i < lang.size(); i++) {
                System.out.println("The " + i + " element of the array: " + lang.get(i));
            }
            Iterator i = lang.iterator();

            // take each value from the json array separately
            while (i.hasNext()) {
                JSONObject innerObj = (JSONObject) i.next();
                System.out.println("language " + innerObj.get("lang") +
                        " with level " + innerObj.get("knowledge"));
            }
            // handle a structure into the json object
            JSONObject structure = (JSONObject) jsonObject.get("job");
            System.out.println("Into job structure, name: " + structure.get("name"));

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

Now let’s explain the code above. After we create an instance of JSONParser, we create a JSONObject by parsing the FileReader of our .json file. This JSONObject contains a collection of key-value pairs, from which we can get every value of the JSON file. To retrieve primitive objects, get() method of the JSONObject's instance is called, defining the specified key as an argument. It is important to add the suitable cast to the method. For array types in JSON file, JSONArray is used that represents an ordered sequence of values. As you can notice in the code, an Iterator should be used in order to take each value of the JSON array. A structure in the JSON file, signs the creation of a new JSONObject in order to retrieve the values.

You can see the output of the execution below.

Output:

The first name is: Katerina
The id is: 1
The 0 element of the array: {"knowledge":"proficient","lang":"en"}
The 1 element of the array: {"knowledge":"advanced","lang":"fr"}
language en with level proficient
language fr with level advanced
Into job structure, name: Java Code Geeks

1.2. GSON parser

In this section, We will cover the Gson library to convert JSON to object and vice versa. Gson can work with arbitrary Java objects including preexisting objects. It also supports the use of Java Generics.

pom.xml

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

This adds the Gson dependency to our project so that we can use it deserialize the JSON into java object.

GsonParseTest.java

public class GsonParseTest {

    private static final String filePath = "jsonTestFile.json";

    public static void main(String[] args) {
        Gson gson = new Gson();
        try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) {
            Person person = gson.fromJson(reader, Person.class);
            System.out.println(person.toString());
       } catch (Exception ex) {
            ex.printStackTrace();
       }
   }
}
  • The first step similar to the above is creating a reader to read the contents of JSON file.
  • We construct and instance of the Gson class.
  • We pass the reader to the fromJson method and provide the class to which it needs to be deserialized.
  • This simple mapping is enough for Gson to deserialize the JSON into Person class.
  • We use the toString method to print out the contents of the Person class.

1.3. Jackson parser

In this section, We will cover the Jackson library to convert JSON to object. Jackson supports data binding for various formats, but we will cover here for JSON data binding.

pom.xml

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

This adds the jackson-databing dependency to our project so that we can use it deserialize the JSON into java object.

JacksonParseTest.java

public class JacksonParseTest {

    private static final String filePath = "jsonTestFile.json";

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) {
            Person person = mapper.readValue(reader, Person.class);
            System.out.println(person.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
   }
}
  • The first step similar to the above is creating a reader to read the contents of JSON file.
  • We construct and instance of the ObjectMapper class.
  • We pass the reader to the readValue method and provide the class to which it needs to be deserialized.
  • This mapping is enough for Jackson to deserialize the JSON into Person class.
  • We use the toString method to print out the contents of the Person class.

1.4. JSON-Java

In this section, We will cover the stleary/JSON-java library to convert JSON to object. It is a reference implementation for converting JSON to java object and vice versa.

pom.xml

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20190722</version>
</dependency>

This adds the org.json.json dependency to our project so that we can use it deserialize the JSON into java object.

StealryJsonTest.java

public class StealryJsonTest {
    private static final String filePath = "jsonTestFile.json";

    public static void main(String[] args) {
        try (FileReader reader = new FileReader(ClassLoader.getSystemResource(filePath).getFile())) {
            JSONTokener tokener = new JSONTokener(reader);
            JSONObject object = new JSONObject(tokener);

            String firstName = (String) object.get("firstname");
            System.out.println("The first name is: " + firstName);

            // get a number from the JSON object
            int id = (int) object.get("id");
            System.out.println("The id is: " + id);

            // get an array from the JSON object
            JSONArray lang = (JSONArray) object.get("languages");

            // take the elements of the json array
            for (int i = 0; i < lang.length(); i++) {
                System.out.println("The " + i + " element of the array: " + lang.get(i));
            }
            Iterator i = lang.iterator();

            // take each value from the json array separately
            while (i.hasNext()) {
                JSONObject innerObj = (JSONObject) i.next();
                System.out.println("language " + innerObj.get("lang") +
                        " with level " + innerObj.get("knowledge"));
            }
            // handle a structure into the json object
            JSONObject structure = (JSONObject) object.get("job");
            System.out.println("Into job structure, name: " + structure.get("name"));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
  • After we create an instance of JSONTokener, we create a JSONObject by parsing the FileReader of our .json file.
  • JSONTokener is used to tokenize and split the JSON string and is passed to the JSONObject for extracting the values.
  • This JSONObject contains a collection of key-value pairs, from which we can get every value of the JSON file.
  • To retrieve primitive objects, get() method of the JSONObject's instance is called, defining the specified key as an argument.
  • For array types in JSON file, JSONArray is used that represents an ordered sequence of values.
  • A structure in the JSON file, signs the creation of a new JSONObject in order to retrieve the values.

1.5. No One-size Fits All

JSON.simple is good for very simple use cases while stleary/JSON-java is more of a reference implementation. Both Gson and Jackson are good candidates for complex use cases. Jackson has the following advantages

  • Built into all JAX-RS (Jersey, Apache CXF, RESTEasy, Restlet), and Spring framework
  • Has Extensive annotation support

Gson has the following advantages

  • Can be used in third party code without annotations.
  • Convenient toJson and fromJson for simplistic use-cases.

The differences between Gson and Jackson even in the simple example. We can change the firstname property of Person class to firstName. Now if we run the previous examples

Jackson

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "firstname" (class com.jcg.jsonParser.Person), not marked as ignorable (4 known properties: "id", "job", "firstName", "languages"])
 at [Source: (FileReader); line: 3, column: 17] (through reference chain: com.jcg.jsonParser.Person["firstname"])
	at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:60)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:822)
	at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1152)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3049)
	at com.jcg.jsonParser.JacksonParseTest.main(JacksonParseTest.java:13)

We get an error as Jackson is unable to deserialize the property firstname and it is not marked as ignorable. Running the same example in Gson, we get the below output

Gson

Person{id='1', firstName='null', languages=[Language{lang='en', knowledge='proficient'}, Language{lang='fr', knowledge='advanced'}], job=Job{site='www.javacodegeeks.com', name='Java Code Geeks'}}

Here, it fails softly by setting the firstName field to null rather than throwing an exception as in case of Jackson.

2. Download the Source Code

Download
Download the source code of this example here: Java JSON parser Example

Last updated on Oct. 07, 2019

Don’t forget to check out our Academy premium site for advanced Java training!

Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ardalan
Ardalan
5 years ago

Hi,
i have a interesting Jason String and i coud not to pars it because looks different.
i just need to take a Status and message can somebody help me?

{“certInfo”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”vulnerabilities”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”serverConfig”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}}}

Stanislav Vincent
Stanislav Vincent
5 years ago
Reply to  Ardalan

Thank you

Captain Francis
Captain Francis
4 years ago
Reply to  Ardalan

JSON structure is not proper

Back to top button