Convert Json to Java Object Using Gson Example

Hello Java Programmers, 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 a 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 that 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 a Java object is known as De-Serialization. You can use any JSON library to perform serialization and de-serialization like Jackson Databind, Gson, or Json-simple.  In this program, I'll show you how to use Gson to create a Java object from a 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 like databases, from 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 little problem. Since JSON String are enclosed with double quotes, they need to be escaped in Java code like every double quote 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 that 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:

How to convert JSON to Java Object using Gson

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 marks 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 like 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.

How to convert a JSON String to Java Object using Gson? DeSerialization Example

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 the 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.

Java Program to convert JSON String to Java Object using Gson

            import            com.google.gson.Gson;            /**  * Java Program to convert JSON String to Java Object using Gson.   *   *              @author              WINDOWS  *  */            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.

Java Gson Example for Beginners



How to compile and run this program?

Similar to the last example, if you are using Maven then you can use the following dependency to download the Gson.jar file automatically. Alternatively, you can manually download Gson.jar from the 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 the steps given here to add any external JAR to the classpath.

That's all about how to convert a JSON String to a Java object using the 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 files 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 it 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 join these Free Java Programming courses, which cover several advanced Java features like JSON, RESTFul Web Services, JAXB, JDBC, etc.

woodregave1949.blogspot.com

Source: https://www.java67.com/2017/05/how-to-convert-json-string-to-java-object-gson-example.html

0 Response to "Convert Json to Java Object Using Gson Example"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel