Gson Tutorial
Gson Useful Resources
Selected Reading
- 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 - Object Data Binding
Gson - Object Data Binding
Object data binding refers to mapping of JSON to any JAVA Object.
//Create a Gson instance Gson gson = new Gson(); //map Student object to JSON content String jsonString = gson.toJson(student); //map JSON content to Student object Student student1 = gson.fromJson(jsonString, Student.class);
Example
Let s see object data binding in action. Here we ll map JAVA Object directly to JSON and vice versa.
Create a Java class file named GsonTester in C:>GSON_WORKSPACE.
File - GsonTester.java
import com.google.gson.Gson; pubpc class GsonTester { pubpc static void main(String args[]) { Gson gson = new Gson(); Student student = new Student(); student.setAge(10); student.setName("Mahesh"); String jsonString = gson.toJson(student); System.out.println(jsonString); Student student1 = gson.fromJson(jsonString, Student.class); System.out.println(student1); } } 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.
{"name":"Mahesh","age":10} Student [ name: Mahesh, age: 10 ]Advertisements