json

Java JSON parser Example

Photo of Katerina ZamaniKaterina ZamaniJanuary 24th, 2014Last Updated: September 24th, 2021
3 8,632 6 minutes read

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 forJSON processing.

1. JSON Parsers

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

1.1. Simple JSON parser

In this section we are going to use a common Java toolkit forJSONJSON.simple. Before start coding we have to set a proper environment for the compiler to recognize theJSON's classes. If you want to build your project via Maven, you should add the following dependency to yourpom.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 insrc/main/resources directory. This file is namedjsonTestFile.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, namedJsonParseTest. 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 ofJSONParser, we create aJSONObject by parsing theFileReader of our.json file. ThisJSONObject 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 theJSONObject'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, anIterator should be used in order to take each value of the JSON array. A structure in the JSON file, signs the creation of a newJSONObject in order to retrieve the values.

You can see the output of the execution below.

Output:

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

1.2. GSON parser

In this section, We will cover theGson 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 theGson 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 theGson class.
  • We pass the reader to thefromJson method and provide the class to which it needs to be deserialized.
  • This simple mapping is enough forGson to deserialize the JSON intoPerson class.
  • We use thetoString method to print out the contents of thePerson class.

1.3. Jackson parser

In this section, We will cover theJackson 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 thejackson-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 theObjectMapper class.
  • We pass the reader to thereadValue method and provide the class to which it needs to be deserialized.
  • This mapping is enough forJackson to deserialize the JSON intoPerson class.
  • We use thetoString method to print out the contents of thePerson class.

1.4. JSON-Java

In this section, We will cover thestleary/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 theorg.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 ofJSONTokener, we create aJSONObject by parsing theFileReader of our.json file.
  • JSONTokener is used to tokenize and split the JSON string and is passed to theJSONObject for extracting the values.
  • ThisJSONObject 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 theJSONObject'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 newJSONObject in order to retrieve the values.

1.5. No One-size Fits All

JSON.simple is good for very simple use cases whilestleary/JSON-java is more of a reference implementation. BothGson andJackson 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.
  • ConvenienttoJson andfromJson for simplistic use-cases.

The differences betweenGson andJackson even in the simple example. We can change thefirstname property ofPerson class tofirstName. 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 asJackson is unable to deserialize the propertyfirstname and it is not marked asignorable. Running the same example inGson, 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 thefirstName field to null rather than throwing an exception as in case ofJackson.

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 ourAcademy premium site for advanced Java training!

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Katerina ZamaniKaterina ZamaniJanuary 24th, 2014Last Updated: September 24th, 2021
3 8,632 6 minutes read
Photo of Katerina Zamani

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.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.