How to convert Java Object to / from JSON (Using Gson)

In this article, you will see how to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at
http://code.google.com/p/google-gson

Add the following dependencies in pom.xml

<dependencies>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.2.2</version>
    </dependency>
</dependencies>

1. Create POJO

Create Person Class as following.

package com.kruders.domain;
 
public class Person {
    private String firstName;
    private String lastName;
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

2. Convert to JSON

You just need to create an instance of Gson class and then call the toJson() method and pass the object to be converted into JSON string.

package com.kruders.gson;
 
import java.util.ArrayList;
import java.util.List;
 
import com.google.gson.Gson;
import com.kruders.domain.Person;
 
public class ConvertToJson {
    public static void main(String args[]) {
        List<Person> personList = new ArrayList<Person>();
        Person p1 = new Person();
        Person p2 = new Person();
        p1.setFirstName("Puneet");
        p1.setLastName("Aggarwal");
        p2.setFirstName("Ankit");
        p2.setLastName("Gupta");
         
        personList.add(p1);
        personList.add(p2);
         
        Gson gson = new Gson();
        System.out.println("json = " + gson.toJson(personList));
    }
}

When you run the example above you’ll get an output like:

json = [{“firstName”:”Puneet”,”lastName”:”Aggarwal”},{“firstName”:”Ankit”,”lastName”:”Gupta”}]

3. JSON to Object

To convert JSON string to object use Gson.fromJson() method. This method takes the JSON string and the object type of the string to be converted.

package com.kruders.gson;
 
import com.google.gson.Gson;
import com.kruders.domain.Person;
 
public class JsonToObject {
    public static void main(String args[]) {
        String json = "{\"firstName\":\"Puneet\",\"lastName\":\"Aggarwal\"}";
        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);
         
        System.out.println("First Name : " + person.getFirstName());
        System.out.println("Last Name : " + person.getLastName());
    }
}

When you run the example above you’ll get an output like:

First Name : Puneet
Last Name : Aggarwal

4. Null Object Support

The default behaviour that is implemented in Gson is that null object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java.

Here’s how you would configure a Gson instance to output null:
Gson gson = new GsonBuilder().serializeNulls().create();

NOTE: when serializing nulls with Gson, it will add a JsonNull element to the JsonElement structure. Therefore, this object can be used in custom serialization/deserialization.

Here’s an example:

package com.kruders.gson;
 
import java.util.ArrayList;
import java.util.List;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kruders.domain.Person;
 
public class NullObjectSupport {
    public static void main(String args[]) {
        List<person> personList = new ArrayList<person>();
        Person p1 = new Person();
        Person p2 = new Person();
        p1.setFirstName("Puneet");
        p1.setLastName(null);
        p2.setFirstName("Ankit");
        p2.setLastName("Gupta");
         
        personList.add(p1);
        personList.add(p2);
         
        Gson gson = new GsonBuilder().serializeNulls().create();
        System.out.println("json = " + gson.toJson(personList));
    }
}

When you run the example above you’ll get an output like:

json = [{“firstName”:”Puneet”,”lastName”:null},{“firstName”:”Ankit”,”lastName”:”Gupta”}]

5. Compact Vs. Pretty Printing for JSON Output Format

The default JSON output that is provide by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, “null” fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the Null Object Support section for information on configure Gson to output all null values.

If you like to use the Pretty Print feature, you must configure your Gson instance using the GsonBuilder. The JsonFormatter is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default JsonPrintFormatter that has default line length of 80 character, 2 character indentation, and 4 character right margin.

The following is an example shows how to configure a Gson instance to use the default JsonPrintFormatter instead of the JsonCompactFormatter:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Here’s an example:

package com.kruders.gson;
 
import java.util.ArrayList;
import java.util.List;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.kruders.domain.Person;
 
public class PrettyPrinting {
    public static void main(String args[]) {
        List<person> personList = new ArrayList<person>();
        Person p1 = new Person();
        Person p2 = new Person();
        p1.setFirstName("Puneet");
        p1.setLastName("Aggarwal");
        p2.setFirstName("Ankit");
        p2.setLastName("Gupta");
         
        personList.add(p1);
        personList.add(p2);
         
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println("json = " + gson.toJson(personList));
    }
}
</person></person>

When you run the example above you’ll get an output like:

json = [
{
“firstName”: “Puneet”,
“lastName”: “Aggarwal”
},
{
“firstName”: “Ankit”,
“lastName”: “Gupta”
}
]

You can download the source code of this example here.

, ,

No comments yet.

Leave a Reply