Gson Tree Model Write and Parse to and From JSON

Gson Tree Model API provides support to read and parse a JSON String into a Tree Model. We can use the JsonParser to parse the JSON string into a Tree Model of type JsonElement.

Gson Tree Model API also supports converting a Java object into a Tree Model using the Gson#toJsonTree() method, which also returns a JsonElement. Using this JsonElement we can manipulate the Tree Model at runtime.

Read and Parse JSON to Gson Tree Model

We can use the JsonParser to convert a JSON string/file into a Tree Model. Once we have the Tree Model we can get all the properties of the model. For the simplicity of the example, we simply print out the values of the properties to the console.

package com.memorynotfound.json;

import com.google.gson.*;

public class ParseJsonTreeModel {

    public static void main(String... args){

        String input = "{\"name\":\"BMW\",\"model\":X1,\"year\":2016,\"colors\":[\"GRAY\",\"BLACK\",\"WHITE\"]}";

        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(input);

        if (element.isJsonObject()){
            JsonObject car = element.getAsJsonObject();
            System.out.println(car.get("name"));
            System.out.println(car.get("model"));
            System.out.println(car.get("year"));

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

    }
}

The previous example generates the following output.

"BMW"
"X1"
2016
"GRAY"
"BLACK"
"WHITE"

Write Gson Tree Model to JSON String

We can convert a Java object into a Tree Model representation by calling the Gson#toJsonTree() method. This returns a JsonElement, which we can use to manipulate the Tree Model. We can add, update or remove elements from the model.

package com.memorynotfound.json;

import com.google.gson.*;
import java.io.IOException;
import java.util.Arrays;

public class WriteJsonTreeModel {

    public static void main(String... args) throws IOException {

        Gson gson = new GsonBuilder().create();

        Car car = new Car("BMW", "X1", 2016, Arrays.asList("BLUE", "RED", "WHITE"));
        JsonElement jsonElement = gson.toJsonTree(car);
        System.out.println("Original JSON: " + jsonElement);

        JsonObject jsonObject = jsonElement.getAsJsonObject();
        jsonObject.addProperty("interior", "BLACK");                  // add property
        jsonObject.addProperty("year", 2017);                       // update property
        jsonObject.remove("year");                                  // remove property

        JsonArray jsonArray = jsonObject.get("colors").getAsJsonArray();
        jsonArray.add("BLACK");                                     // add element
        jsonArray.set(0, new JsonPrimitive("YELLOW"));              // update element
        jsonArray.remove(1);                                        // remove element

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

The representation of the car model.

package com.memorynotfound.json;

import java.util.List;

public class Car {

    private String name;
    private String model;
    private int year;
    private List colors;

    public Car(String name, String model, int year, List colors) {
        this.name = name;
        this.model = model;
        this.year = year;
        this.colors = colors;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", model='" + model + '\'' +
                ", year=" + year +
                ", colors=" + colors +
                '}';
    }
}

The previous code generates the following output.

Original JSON: {"name":"BMW","model":"X1","year":2016,"colors":["BLUE","RED","WHITE"]}
Updated JSON: {"name":"BMW","model":"X1","colors":["YELLOW","WHITE","BLACK"],"interior":"BLACK"}

You may also like...