Top two features of GSON

Exclusive offer: get 50% off this eBook here
Instant GSON [Instant]

Instant GSON [Instant] — Save 50%

Learn to create JSON data from Java objects and implement them in an application with the GSON library with this book and ebook

$14.99    $7.50
by Sandeep Kumar Patel | September 2013 | Open Source

In this article, by Sandeep Kumar Patel, the author of Instant GSON, you will learn about the top features supported by the GSON library. You will also learn about how to implement these features.

(For more resources related to this topic, see here.)

Java objects support

Objects in GSON are referred as types of JsonElement:

The GSON library can convert any user-defined class objects to and from the JSON representation. The Student class is a user-defined class, and GSON can serialize any Student object to JSON.

The Student.java class is as follows:

public class Student { private String name; private String subject; privateint mark; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public int getMark() { return mark; } public void setMark(int mark) { this.mark = mark; } }

The code for JavaObjectFeaturesUse.java is as follows:

import com.google.gson.Gson; import com.packt.chapter.vo.Student; public class JavaObjectFeaturesUse { public static void main(String[] args){ Gsongson = new Gson(); Student aStudent = new Student(); aStudent.setName("Sandeep"); aStudent.setMark(128); aStudent.setSubject("Computer Science"); String studentJson = gson.toJson(aStudent); System.out.println(studentJson); Student anotherStudent = gson.fromJson(studentJson, Student.class); System.out.println(anotherStudentinstanceof Student); } }

The output of the preceding code is as follows:

{"name":"Sandeep","subject":"Computer Science","mark":128} True

The preceding code creates a Student object with name as Sandeep, subject as Computer Science, and marks as 128. A Gson object is then instantiated and the Student object is passed in as a parameter to the toJson() method. It returns a string that has the JSON representation of the Java object. This string is printed as the first line in the console. The output JSON representation of the Student object is a collection of key/value pairs. The Java property of the Student class becomes the key in the JSON string.

In the last part of the code, the fromJson() method takes the JSON generated string as the first input parameter and Student.class as the second parameter, to convert the JSON string back to a Student Java object. The last line of the code uses an instance of Student as the second-line operator to verify whether the generated Java object by the fromJson() method is of type Student. In the console, it prints True as the output, and if we print the values, we will get the same values as in JSON.

Serialization and deserialization

GSON has implicit serializations for some classes, such as Java wrapper type (Integer, Long, Double, and so on), java.net.URL, java.net.URI, java.util.Date, and so on.

Let's see an example:

import java.util.Date; import com.google.gson.Gson; public class InbuiltSerializerFeature { public static void main(String[] args) { Date aDateJson = new Date(); Gsongson = new Gson(); String jsonDate = gson.toJson(aDateJson); System.out.println(jsonDate); } }

The output of the preceding code is as follows:

May 29, 2013 8:55:07 PM

The preceding code is serializing the Java Date class object to its JSON representation. In the preceding section, you have learned how GSON is used to serialize and deserialize objects, and how it supports custom serializers and deserializers for user-defined Java class objects. Let's see how it works.

Also, GSON provides the custom serialization feature to developers.

The following code is an example of a custom serializer:

classStudentTypeSerializer implements JsonSerializer<Student>{ @Override publicJsonElement serialize(Student student, Type type, JsonSerializationContextcontext) { JsonObjectobj = new JsonObject(); obj.addProperty("studentname", student.getName()); obj.addProperty("subjecttaken", student.getSubject()); obj.addProperty("marksecured", student.getMark()); returnobj; } }

The following code is an example of a custom deserializer:

classStudentTypeDeserializer implements JsonDeserializer<Student>{ @Override public Student deserialize(JsonElementjsonelment, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObjectjsonObject = jsonelment.getAsJsonObject(); Student aStudent = new Student(); aStudent.setName(jsonObject.get("studentname").getAsString()); aStudent.setSubject(jsonObject.get("subjecttaken").getAsString()); aStudent.setMark(jsonObject.get("marksecured").getAsInt()); return aStudent; } }

The following code tests the custom serializer and deserializer:

import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class CustomSerializerFeature { public static void main(String[] args) { GsonBuildergsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Student.class, new StudentTypeSerializer()); Gsongson = gsonBuilder.create(); Student aStudent = new Student(); aStudent.setName("Sandeep"); aStudent.setMark(150); aStudent.setSubject("Arithmetic"); String studentJson = gson.toJson(aStudent); System.out.println("Custom Serializer : Json String Representation "); System.out.println(studentJson); Student anotherStudent = gson.fromJson(studentJson, Student.class); System.out.println("Custom DeSerializer : Java Object Creation"); System.out.println("Student Name "+anotherStudent.getName()); System.out.println("Student Mark "+anotherStudent.getMark()); System.out.println("Student Subject "+anotherStudent.getSubject()); System.out.println("is anotherStudent is type of Student "+(anotherStudentinstanceof Student)); } }

The output of the preceding code is as follows:

Custom Serializer : Json String Representation

{"studentname":"Sandeep","subjecttaken":"Arithmetic","marksecured":150}

Custom DeSerializer : Java Object Creation

Student Name Sandeep

Student Mark 150

Student Subject Arithmetic

is anotherStudent is type of Student true

Summary

This section explains about the support of Java objects and how to implement serialization and deserialization in GSON.

Resources for Article :


Further resources on this subject:


Instant GSON [Instant] Learn to create JSON data from Java objects and implement them in an application with the GSON library with this book and ebook
Published: August 2013
eBook Price: $14.99
See more
Select your format and quantity:

About the Author :


Sandeep Kumar Patel

Sandeep Kumar Patel is a senior web developer and founder of www.tutorialsavvy.com, a widely- read programming blog since 2012. He has more than four years of experience in object-oriented JavaScript and JSON-based web applications development. He is GATE-2005 Information Technology (IT) qualified and has a Masters degree from VIT University, Vellore. At present, he holds the position of senior development engineer in Pramati Technology. You can know more about him from his LinkedIn profile (http://www.linkedin.com/in/techblogger).

He has received the Dzone Most Valuable Blogger (MVB) award for technical publications related to web technologies. His article can be viewed at http://www.dzone.com/users/sandeepgiet.

He has also received the Java Code Geek (JCG) badge for a technical article published in JCG. His article can be viewed at http://www.javacodegeeks.com/author/sandeep-kumar-patel/.

Books From Packt


Instant Kendo UI Grid
Instant Kendo UI Grid

jQuery UI 1.6: The User Interface Library for jQuery
jQuery UI 1.6: The User Interface Library for jQuery

PHP jQuery Cookbook
PHP jQuery Cookbook

PHP Web 2.0 Mashup Projects: Practical PHP Mashups with Google Maps, Flickr, Amazon, YouTube, MSN Search, Yahoo!
PHP Web 2.0 Mashup Projects: Practical PHP Mashups with Google Maps, Flickr, Amazon, YouTube, MSN Search, Yahoo!

Object-Oriented JavaScript
Object-Oriented JavaScript

Developing RESTful Services with JAX-RS 2.0, WebSockets and JSON
Developing RESTful Services with JAX-RS 2.0, WebSockets and JSON

Learning Dojo
Learning Dojo

Instant AngularJS Starter
Instant AngularJS Starter


Your rating: None Average: 5 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
5
T
g
1
T
H
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software