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 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 forJSON –JSON.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 Geeks1.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 the
Gsonclass. - We pass the reader to the
fromJsonmethod and provide the class to which it needs to be deserialized. - This simple mapping is enough for
Gsonto deserialize the JSON intoPersonclass. - We use the
toStringmethod to print out the contents of thePersonclass.
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 the
ObjectMapperclass. - We pass the reader to the
readValuemethod and provide the class to which it needs to be deserialized. - This mapping is enough for
Jacksonto deserialize the JSON intoPersonclass. - We use the
toStringmethod to print out the contents of thePersonclass.
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 of
JSONTokener, we create aJSONObjectby parsing theFileReaderof our.jsonfile. JSONTokeneris used to tokenize and split the JSON string and is passed to theJSONObjectfor extracting the values.- This
JSONObjectcontains 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'sinstance is called, defining the specified key as an argument. - For array types in JSON file,
JSONArrayis used that represents an ordered sequence of values. - A structure in the JSON file, signs the creation of a new
JSONObjectin 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.
- Convenient
toJsonandfromJsonfor 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 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!

Thank you!
We will contact you soon.



