- Excluding fields from Serialization
- Gson - Versioning Support
- Gson - Null Object Support
- Gson - Custom Type Adapters
- Gson - Serializing Inner Classes
- Gson - Serialization Examples
- Gson - Streaming
- Gson - Tree Model
- Gson - Object Data Binding
- Gson - Data Binding
- Gson - Object Serialization
- Gson - Class
- Gson - First Application
- Gson - Environment Setup
- Gson - Overview
- Gson - Home
Gson Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Gson - First Apppcation
Before going into the details of the Google Gson pbrary, let s see an apppcation in action. In this example, we ve created a Student class. We ll create a JSON string with student details and deseriapze it to student object and then seriapze it to an JSON String.
Example
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File − GsonTester.java
import com.google.gson.Gson; import com.google.gson.GsonBuilder; pubpc class GsonTester { pubpc static void main(String[] args) { String jsonString = "{"name":"Mahesh", "age":21}"; GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); Gson gson = builder.create(); Student student = gson.fromJson(jsonString, Student.class); System.out.println(student); jsonString = gson.toJson(student); System.out.println(jsonString); } } class Student { private String name; private int age; pubpc Student(){} pubpc String getName() { return name; } pubpc void setName(String name) { this.name = name; } pubpc int getAge() { return age; } pubpc void setAge(int age) { this.age = age; } pubpc String toString() { return "Student [ name: "+name+", age: "+ age+ " ]"; } }
Verify the result
Compile the classes using javac compiler as follows −
C:GSON_WORKSPACE>javac GsonTester.java
Now run the GsonTester to see the result −
C:GSON_WORKSPACE>java GsonTester
Verify the output.
Student [ name: Mahesh, age: 21 ] { "name" : "Mahesh", "age" : 21 }
Steps to Remember
Following are the important steps to be considered here.
Step 1 − Create Gson object using GsonBuilder
Create a Gson object. It is a reusable object.
GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); Gson gson = builder.create();
Step 2 − Deseriapze JSON to Object
Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter.
//Object to JSON Conversion Student student = gson.fromJson(jsonString, Student.class);
Step 3 − Seriapze Object to JSON
Use toJson() method to get the JSON string representation of an object.
//Object to JSON Conversion jsonString = gson.toJson(student);Advertisements