Categories: Json

Gson Tree Model Example

Similar to Jackson API, Google GSON API provides a conceptual tree notion for JSON. Google Gson Tree model API provides com.google.gson.JsonParser which can be used to parse the input JSON string into a tree of com.google.gson.JsonElement. On reading side, JsonElement provides isJsonXXX methods to check the type of Json element and getAsYYY() methods to get the actual data on that tree node.

On the writing end, core com.google.gson.Gson api provides toJsonTree method which converts a java object into a conceptual tree node JsonElement. JsonElement can then return JsonObject which provides addProperty methods to add individual fields/property on that JsonObject and create/construct the complete tree whose elements can be updated at run time.


Complete Example

Step 1: Include Google GSON dependency in pom.xml

<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>GsonTreeModelExample</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <name>GsonTreeModelExample</name>

 <dependencies>
  <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.3.1</version>
  </dependency>
 </dependencies>
</project>

Step 2: Read Input JSON string into Tree model

Sample input file input.json used in below Main

{"name":"AUDI","model":2014,"price":30000,"colors":["GRAY","BLACK","WHITE"]}
package com.websystique.json.gson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JsonGsonTreeModelReadExample {

 public static void main(String[] args) throws FileNotFoundException {

  FileReader reader = new FileReader(new File("input.json"));

  JsonParser parser = new JsonParser();
  JsonElement element = parser.parse(reader);// Returns Root element(
             // which is a JsonElement,
             // can be object,array, null
             // or primitive)

  if (element.isJsonObject()) {
   JsonObject car = element.getAsJsonObject();
   System.out.println(car.get("name").getAsString());//read as string
   System.out.println(car.get("model").getAsInt());  //read as integer
   System.out.println(car.get("price").getAsDouble());//read as double

   JsonArray arr = car.getAsJsonArray("colors");//read as array
   for (int i = 0; i < arr.size(); i++) {
    System.out.println(arr.get(i).getAsString());
   }
  }

 }
}

Run it. Following output is generated:

AUDI
2014
30000.0
GRAY
BLACK
WHITE

Step 2: Write Tree model into Json String

package com.websystique.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

public class JsonGsonTreeModelWriteExample {

 public static void main(String args[]) {
  JsonGsonTreeModelWriteExample ex = new JsonGsonTreeModelWriteExample();
  Car car = ex.getCar();

  Gson gson = new GsonBuilder().create();
  JsonElement jsonElement = gson.toJsonTree(car);     
  System.out.println("Original JSON : " + jsonElement);    // Root element

  JsonObject jsonObject = jsonElement.getAsJsonObject();
  jsonObject.addProperty("power", "300BHP");       // add a new property

  jsonObject.remove("cost");           // remove an existing property
  
  jsonObject.getAsJsonArray("colors").set(0, new JsonPrimitive("RED"));// update an existing property

  System.out.println("Updated JSON : " + jsonObject);
 }

 private Car getCar() {
  Car car = new Car();
  car.setName("AUDI");
  car.setModel(2014);
  car.setCost(45000);
  car.getColors().add("GREY");
  car.getColors().add("BLACK");
  car.getColors().add("WHITE");
  return car;
 }

}
package com.websystique.json.gson;

import java.util.ArrayList;
import java.util.List;

public class Car {
 private String name;
 private int model;
 private double cost;
 
 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 getCost() {
  return cost;
 }

 public void setCost(double cost) {
  this.cost = cost;
 }

 public List<String> getColors() {
  return colors;
 }

 public void setColors(List<String> colors) {
  this.colors = colors;
 }
 
}

Run it. Following output is generated:

Original JSON : {"name":"AUDI","model":2014,"cost":45000.0,"colors":["GREY","BLACK","WHITE"]}
Updated JSON : {"name":"AUDI","model":2014,"colors":["RED","BLACK","WHITE"],"power":"300BHP"}

That’s it. In the next post we will learn about Google Gson Streaming API.

References

Share
Published by

Recent Posts

Spring Boot + AngularJS + Spring Data + JPA CRUD App Example

In this post we will be developing a full-blown CRUD application using Spring Boot, AngularJS, Spring Data, JPA/Hibernate and MySQL,…

7 years ago

Spring Boot Rest API Example

Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot…

7 years ago

Spring Boot WAR deployment example

Being able to start the application as standalone jar is great, but sometimes it might not be possible to run…

7 years ago

Spring Boot Introduction + hello world example

Spring framework has taken the software development industry by storm. Dependency Injection, rock solid MVC framework, Transaction management, messaging support,…

7 years ago

Secure Spring REST API using OAuth2

Let's secure our Spring REST API using OAuth2 this time, a simple guide showing what is required to secure a…

8 years ago

AngularJS+Spring Security using Basic Authentication

This post shows how an AngularJS application can consume a REST API which is secured with Basic authentication using Spring…

8 years ago