This post explains converting Java object to/from JSON using Google GSON library
. To get hold of JSON Basics concepts, please refer to JSON basics. Let’s get going.
com.google.gson.Gson
is the main class used for converting JSON to/from java objects. This class provides toJson
& fromJson
methods to convert Java object to/from JSON. Gson library also provides com.google.gson.GsonBuilder
which is essentially a builder to create instances of Gson with additional configuration options. Typical usages are as follows:
//Create gson instance Gson gson = new Gson(); //or use GsonBuilder to create a Gson instance with some additional configuration Gson gson = new GsonBuilder().setPrettyPrinting().create();
//Convert Java object to JSON String jsonString = gson.toJson(java_object);
//Read JSON and populate java objects //convert JSON to Java object Car car = gson.fromJson(jsonString, Car.class);
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.websystique.json</groupId> <artifactId>GsonObjectToJsonExample</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>GsonObjectToJsonExample</name> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> </dependencies> </project>
This object will be converted to and from JSON.
package com.websystique.json.gson.model; import java.util.ArrayList; import java.util.List; public class Car { private String name; private int model; private double price; private List<String> colors = new ArrayList<String>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public int getModel() { return model; } public void setModel(int model) { this.model = model; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public List<String> getColors() { return colors; } public void setColors(List<String> colors) { this.colors = colors; } @Override public String toString() { return "Car [name=" + name + ", model=" + model + ", price=" + price + ", colors=" + colors + "]"; } }
Convert Car object into JSON using toJson
method
package com.websystique.json.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.websystique.json.gson.model.Car; public class GsonObjectToJsonDemo { public static void main(String args[]){ Gson gson = new Gson(); //Gson gson = new GsonBuilder().setPrettyPrinting().create(); //Toggle comment for Pretty print JSON Car car = new Car(); car.setName("AUDI"); car.setModel(2014); car.setPrice(30000); car.getColors().add("GRAY"); car.getColors().add("BLACK"); car.getColors().add("WHITE"); String jsonString = gson.toJson(car); // Convert car object to JSON string System.out.println(jsonString); } }
Run above program. Following is the output
{"name":"AUDI","model":2014,"price":30000.0,"colors":["GRAY","BLACK","WHITE"]}
You can pretty print JSON using GsonBuilder setPrettyPrinting
. Just toggle the comment above, following is the output.
{ "name": "AUDI", "model": 2014, "price": 30000.0, "colors": [ "GRAY", "BLACK", "WHITE" ] }
Convert JSON string to Car object using fromJson
method
package com.websystique.json.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.websystique.json.gson.model.Car; public class GsonObjectToJsonDemo { public static void main(String args[]){ Gson gson = new Gson(); //Gson gson = new GsonBuilder().setPrettyPrinting().create(); //Toggle comment for Pretty print JSON String jsonString = "{\"name\":\"AUDI\",\"model\":2014, \"price\":30000,\"colors\":[\"GRAY\",\"BLACK\",\"WHITE\"]}"; Car car = gson.fromJson(jsonString, Car.class);// Convert JSON String to car object System.out.println(car); } }
Run above program. Following is the output
Car [name=AUDI, model=2014, price=30000.0, colors=[GRAY, BLACK, WHITE]]
That’s it. In the next post we will learn how Json can be represented as a conceptual Tree.
References
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.
In this post we will be developing a full-blown CRUD application using Spring Boot, AngularJS, Spring Data, JPA/Hibernate and MySQL,…
Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot…
Being able to start the application as standalone jar is great, but sometimes it might not be possible to run…
Spring framework has taken the software development industry by storm. Dependency Injection, rock solid MVC framework, Transaction management, messaging support,…
Let's secure our Spring REST API using OAuth2 this time, a simple guide showing what is required to secure a…
This post shows how an AngularJS application can consume a REST API which is secured with Basic authentication using Spring…
View Comments
How to get data from pojo class inti text view ?
nice one