This post will discuss how to parse JSON in Java using Google’s Gson and Jackson library.

Nowadays, almost all RESTful web services consume and produce JSON data instead of XML. Unfortunately, Java SE doesn’t support converting JSON to Java Object (and vice-versa). But there are many third-party libraries available that are very reliable and offer high performance.

To use Gson or Jackson library, we need to create POJO (Plain Old Java Object) with the same JSON structure. POJO is simply a class with private fields and public “getter” and “setter” methods. We recommend this online tool jsonschema2pojo for quickly generating POJO from json or json schema with Jackson/Gson annotation style.

1. Using Gson

Google’s Gson is one of the best libraries for parsing a JSON into POJO. It is very easy to learn and implement. We can use the Gson#fromJson() method to convert our JSON string into a Java object.

The following code decodes the given json string with the help of the Gson library:

Download Code

Output:

JSON string is: {"name":"Jon Snow","age":22,"student":{"id":"Jon_Snow_22","subjects":["Maths","Science"]}}
Person object: [Jon Snow, 22, [Jon_Snow_22, [Maths, Science]]]

2. Using Jackson

Jackson is a multi-purpose, high-performance Java library for processing JSON. It provides Data Binding functionality that can be used for binding a JSON string into a POJO. All we need is to call the readValue() method of Jackson’s ObjectMapper class to convert our JSON string into the specified Java object.

Consider the following code, which parses the given json string using the Jackson library:

Download Code

Output:


JSON string is: {"name":"Jon Snow","age":22,"student":{"id":"Jon_Snow_22","subjects":["Maths","Science"]}}
Person object: [Jon Snow, 22, [Jon_Snow_22, [Maths, Science]]]

 
Useful JSON Tools:

That’s all about parsing JSON in Java using Google’s Gson and Jackson Library.