Gson Tutorial: Guide to JSON Parsing in Java
All modern applications generally fetch data from remote services (e.g. REST or SOAP) that is mostly either XML or JSON format. Gson helps applications in Java-JSON serialization and deserialization automatically (as well as manually, if needed, using simple toJson() and fromJson() methods).
Gson can work with arbitrary Java objects including pre-existing objects that we do not have sourcecode of. The best benefit of Gson is that it does not make it mandatory to add annotations into Java classes until we are doing something very specific for certain member fields.
Note that the Gson instance does not maintain any state while invoking JSON operations. It makes the Gson instance to be thread-safe. So, we are free to reuse the same object for multiple JSON serialization and deserialization operations.
Refer to the latest version of Gson from its Maven repo page.
com.google.code.gson gson 2.9.0
The Gradle dependency is as follows:
The most straightforward way to have a Gson instance is to call its default empty constructor. It creates the Gson instance with the following default configurations:
- Generates compact JSON representations by removing all the unneeded whitespaces.
- Omits all the fields that are null. The nulls in arrays are kept as is.
- Uses the default Date format is the same as DateFormat.DEFAULT that ignores the millisecond portion.
- Excludes transient or static fields from consideration for serialization and deserialization.
- Ignores @Expose and @Since annotations.
To override the default configuration, we can use the GsonBuilder class. After calling its constructor, we can call its various configuration methods and finally call create() to get the Gson instance.
Gson gson = new GsonBuilder() .registerTypeAdapter(Id.class, new IdTypeAdapter()) .enableComplexMapKeySerialization() .serializeNulls() .setDateFormat(DateFormat.LONG) .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .setPrettyPrinting() .setVersion(1.0) .create();
To convert a Java object to a JSON string, use the Gson instance to call the function toJson() and pass the object.
User user = new User(); Gson gson = new Gson(); String json = gson.toJson(user);
Similarly, to convert the JSON string to a Java object, use the fromJson() method.
String json = . ; Gson gson = new Gson(); User user = gson.fromJson(json, User.class);
In most cases, Gson library is smart enough to create instances even if any class does not provide a default no-args constructor. But, if we found any problem using a class that does not contain no-args constructor, we can use InstanceCreator support. You need to register the InstanceCreator of a java class type with Gson first before using it.
For example, Department does not have any default no-arg constructor.
public class Department < public Department(String deptName)< this.deptName = deptName; >private String deptName; //Settes, getters and toString() >
And our Employee class has a reference of Department as:
public class Employee < private Integer id; private String firstName; private String lastName; private Listroles; private Department department; //Department reference //Other setters and getters >
To use Department class correctly, we need to register an InstanceCreator for Department as below:
class DepartmentInstanceCreator implements InstanceCreator < public Department createInstance(Type type) < return new Department("None"); >>
Now use the above InstanceCreator as below.
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator()); Gson gson = gsonBuilder.create(); System.out.println( gson.fromJson(">", Employee.class));
Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], department=Department [deptName=Finance]]
5. Custom Serialization and Deserialization
We often need to write/read the JSON values which are not the default representation of the java object. In that case, we need to write a custom serializer and deserializer of that java type.
In our example, I am writing a serializer and deserializer for java.util.Date class, which will help write the Date format in “dd/MM/yyyy” format.
import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class DateSerializer implements JsonSerializer < private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) < return new JsonPrimitive(dateFormat.format(date)); >>
import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; public class DateDeserializer implements JsonDeserializer < private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context) < try < return dateFormat.parse(dateStr.getAsString()); >catch (ParseException e) < e.printStackTrace(); >return null; > >
Now you can register these serializer and deserializer with GsonBuilder as below:
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
The default JSON output that is provide by Gson is a compact JSON format. This means that there will not be any white-space in the output JSON structure. To generate a more readable and pretty looking JSON use setPrettyPrinting() in GsonBuilder .
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonOutput = gson.toJson(employee);
7. Versioning Support with @Since
This is excellent feature you can use, if the class file you are working has been modified in different versions and fields has been annotated with @Since . All you need to do is to use setVersion() method of GsonBuilder .
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer()); //Specify the version like this gsonBuilder.setVersion(1.0); Gson gson = gsonBuilder.create();
The following is an example of fields added in various versions in Employee.java.
public class Employee < @Since(1.0) private Integer id; private String firstName; private String lastName; @Since(1.1) private Listroles; @Since(1.2) private Date birthDate; //Setters and Getters >
Let us see an example of serialization with versioning support.
//Using version 1.0 fields gsonBuilder.setVersion(1.0); Output: ///////////////////////////////////////////////////////////// //Using version 1.1 fields gsonBuilder.setVersion(1.1); Output: ///////////////////////////////////////////////////////////// //Using version 1.2 fields gsonBuilder.setVersion(1.2); Output:
In this first part, we will learn the Google Gson library and its basic mapping functionality.
- Installation – Learn to include gson dependency in the java applications using build tools like maven, Gradle or simple jar file.
- Simple Serialization and Deserialization – Learn to use GSON to serialize a simple Java Object into the JSON representation and to deserialize the JSON string to an equivalent Java object.
- Compact Vs. Pretty Printing for JSON Output Format – The default JSON output that is provided by Gson is a compact JSON format. Use the Pretty Print feature to format the JSON for reading purposes.
- Mapping of Arrays and Lists of Objects – Learn to use Google GSON library to deserialize or parse JSON, containing JSON arrays, to Java arrays or List objects.
- Mapping of Sets – Learn to use Google GSON library to deserialize or parse JSON to Set (e.g. HashSet) in java.
- Mapping of Maps – Learn to serialize HashMap using Google Gson library. Also, learn to deserialize JSON strings to HashMap containing custom Objects using Gson such that field values are copied into appropriate generic types.
The basic examples in the first part are good enough for default usecases. We may need to customize the behavior of Gson to support specific requirements. Learn how to do this.
- Customize Gson object with GsonBuilder – For simple usecases, using ‘Gson gson = new Gson();’ is enough. Learn to use GsonBuilder to create a new Gson instance with the customized configuration.
- Serialize Null Values – By default, Gson omits the null values. Learn to include null values during serialization and deserialization.
- Versioning Support – Multiple versions of the same object can be maintained by using @Since annotation. Gson will ignore Gson any field/object that is greater than the configured version number.
- Custom field names using @SerializedName – Learn to use Google GSON library to serialize Java Objects into their JSON representation and to deserialize a JSON string to an equivalent Java object.
- Excluding Fields From Serialization and Deserialization – Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Learn how to use them.
- JsonReader – Streaming JSON parser – Learn to read a JSON string or file as a stream of JSON tokens.
- JsonParser, JsonElement and JsonObject – Learn to parse a JSON string or stream into a tree structure of Java objects into JsonElement.
- Custom Serialization and Deserialization – Learn to parse a JSON string or stream into a tree structure of Java objects into JsonElement.
- We can configure Gson with Spring Boot applications as the preferred JSON mapper. By default, Spring boot uses Jackson for this purpose.
- We can configure Gson with Jersey as well.
Drop me your questions related to this gson tutorial.
Deserializing Json to a Java Object Using Google’s Gson Library
Join the DZone community and get the full member experience.
javascript object notation (json) is fast becoming the de facto standard or format for transferring, sharing and passing around data. be it on the web, rest service, a remote procedure call or even an ajax request. json is light weight with little memory footprint when compared to an xml.
the content of a json string in its raw form when observed looks gibberish. to make the content usable it needs to be deserialized or converted to a useable form usually a java object (pojo) or an array or list of objects depending on the json content.
a typical json string is as shown below
there are a lot of frameworks for deserializing json to a java object such as json-rpc , gson , flexjson and a whole lots of other open source libraries. of all the libraries mentioned i would in this blog post demonstrate how to use google-gson library to deserialize a json string to a java object. you can download the gson library from https://code.google.com/p/google-gson/ .
to have the json string deserialized, a java object must be created that has the same fields names with the fields in the json string. there is a website that provides a service for viewing the content of a json string in a tree like manner. http://jsonviewer.stack.hu
paste the json string in the text tab
and view the fields and the content from the viewer tab
i would deserialize a json string that contains address details to an address pojo, the address object follows the structure as seen from the json tree view above.
public class address < private string city; private string country; private string housenumber; private string lga; private string state; private string streetname; private string village; private string ward; public string getcity() < return city; >public void setcity(string city) < this.city = city; >public string getcountry() < return country; >public void setcountry(string country) < this.country = country; >public string gethousenumber() < return housenumber; >public void sethousenumber(string housenumber) < this.housenumber = housenumber; >public string getlga() < return lga; >public void setlga(string lga) < this.lga = lga; >public string getstate() < return state; >public void setstate(string state) < this.state = state; >public string getstreetname() < return streetname; >public void setstreetname(string streetname) < this.streetname = streetname; >public string getvillage() < return village; >public void setvillage(string village) < this.village = village; >public string getward() < return ward; >public void setward(string ward) < this.ward = ward; >@override public string tostring() < return "address [city=" + city + ", country=" + country + ", housenumber=" + housenumber + ", lga=" + lga + ", state=" + state + ", streetname=" + streetname + ", village=" + village + ", ward=" + ward + "]"; >>
to perform the deserialization with gson is easy, create pojo classes to hold your data, import the packages com.google.gson.gson and com.google.gson.gsonbuilder, to your project. then create and instance of the gson class and then perform the deserialization as shown below.
gson gson = new gsonbuilder().create(); address address=gson.fromjson(json, address.class);
voila, you have your json deserialized!
the source code listing is below.
package jsondeserializer import com.google.gson.gson; import com.google.gson.gsonbuilder; public class tester < public static void main(string[] args) < string json =""; gson gson = new gsonbuilder().create(); address address=gson.fromjson(json, address.class); system.out.println(address.tostring()); > >
Published at DZone with permission of Ayobami Adewole , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.