How to convert JSON String to Java Object - Gson/JSON Deserialization Example

In the last article, you have learned how to convert a Java object to JSON String and in today's article, you will learn the opposite, i.e. converting a JSON String to Java object. The first example was known as JSON serialization example and this one is known as JSON deserialization because we are creating a Java object from a String. The idea is very similar to classical Serialization in Java where you convert a Java object to another binary format which can be transported over the network or can be saved in the disk for further usage. That's why the process of converting a Java object to JSON is known as serialization and converting a JSON document to Java object is known as De-Serialization. You can use any JSON library to perform serialization and de-serialization e.g. Jackson Databind, Gson, or Json-simple.  In this program, I'll show you how to use Gson to create a Java object from given JSON String.

In order to start with, we need a JSON String. In the real world, you can receive JSON String from many different sources e.g. database, from a RESTful Web Services or any upstream but here we can use the one we have created in the last article:

{
"name": "John",
"email": "john.doe@gmail.com",
"age": 29,
"phone" : 5168161922,
"city" : "NewYork",
"hasCreditCard": false
}

While using JSON String in Java code, there is a littlie problem. Since JSON String are enclosed with double quotes, they need to be escaped in Java code e.g. every double quotes i.e. " needs to write as \". This can be a big problem if your JSON String is more than a couple of values, thankfully there are a couple of ways to solve this problem.



1) Using Eclipse to escape String automatically
Eclipse has this feature which automatically escapes any character inside String literal when you paste a String in code. Which means double quotes around JSON keys can automatically be replaced whenever you enable this setting in Eclipse as shown below:



You can see this tutorial to learn more about how to enable escape String setting in Eclipse and how to automatically escape JSON String in Java.




2) Use Single Quotes
Even though JSON standard defines that JSON properties should be wrapped in quotation mark or double quotes " ", you can use single quotes to avoid tons of \" Java escaping in your String. Thankfully, Gson accepts keys in both single quotes and double quotes e.g. you can write either "name" or 'name', both are valid. Using single quotes or apostrophes will make your code more readable, as shown below:

String json = "{
'name':'John',
 'email':'john.doe@gmail.com',
 'age':29,
 'phone':5168161922,
 'city':'NewYork',
 'hasCreditCard':false
 }";

You can see here we don't need to escape any String inside JSON, which makes it more readable.




Steps to convert a JSON String to Java Object (De-Serialization)

Here are the basic steps to convert a JSON String to Java using Google's Gson library. Basically, you give a JSON document to Gson and it will return a Java object, whose field is populated using values given in JSON String. Since Gson doesn't know which class of object given JSON needs to be converted, you also need to tell him the class name.

1) Download Gson library and add JAR into the classpath, if you are using Maven just add the dependency in your pom.xml file.

2) Create the String you want to convert into a Java object.

3) Create the object of Gson class, a helper class to convert a JSON String to a java object.

4) Call the Gson.fromJSon(json, UserDetails.class) to convert the given JSON String to object of the class given as the second argument. This method returns a Java object whose fields are populated using values given in JSON String.

good books to learn core Java

Java Program to convert JSON String to Java Object

import com.google.gson.Gson;

/**
 * Java Program to convert JSON String to Java Object using Gson. 
 * 
 * @author WINDOWS 8
 *
 */
public class App {

  public static void main(String args[]) {

    String json = "{ 'name':'John', 'email':'john.doe@gmail.com',
     'age':29, 'phone':5168161922, 'city':'NewYork', 'hasCreditCard':false }";
    
    Gson gson = new Gson();
    
    UserDetails user = gson.fromJson(json, UserDetails.class);
    
    System.out.println(user);
    
  }

}

class UserDetails {

  private String name;
  private String email;
  private int age;
  private long phone;
  private String city;
  private boolean hasCreditCard;

}

You can see how we have to pass the class of the expected Java object as the second parameter. Otherwise, Gson doesn't know which object it needs to map given JSON String.

When you print the user object you can see that it contains the values from the provided JSON String. You can also see those values in the debugger if you are using Eclipse for debugging as shown in the following screenshot.



How to compile and run this program?

Similar to the last example, if you are using Maven then you can use following dependency to download Gson.jar file automatically. Alternatively, you can manually download Gson.jar from Maven Central library and put it on your application's classpath.

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

If you have trouble running a program in Eclipse, see here, or, if you are running the program from the command line then you can follow steps given here to add any external JAR to the classpath.


That's all about how to convert a JSON String to Java object using Gson library. It is very simple, you just need to use the fromJson() method of Gson class and you are done. This is the simplest way to convert a JSON String in Java, I don't think it can get any simpler than this. You just need to include the Gson.jar file in your application's classpath or even better just use Maven or Gradle to manage dependencies and get rid of manual downloading JAR and adding into classpath stuff.

Other Java JSON tutorials you may like
  • How to convert JSON array to String array in Java? (answer)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • How to use Google Protocol Buffer in Java? (tutorial)
  • How to parse large JSON file using Jackson Streaming API? (example)
  • 5 Books to Learn REST and RESTful Web Services (books)
  • What is the purpose of different HTTP methods in REST? (see here)
  • How to consume JSON from RESTful Web Services using RestTemplate of Spring? (tutorial)
  • How to convert JSON to HashMap and vice-versa (tutorial)

Thanks for reading this article. If you like this article then please share with your friends and colleagues, if you have any questions or feedback then please drop a comment.

P.S. - If you want to learn more about the advanced topic in Java, I also suggest you reading "Core Java Volume 2 - Advanced Features" By Cay S. Horstmann, it covers several advanced Java features e.g. JAXB, JDBC etc. 

No comments:

Post a Comment