How to add/insert additional property to JSON string using Gson in Java?


The com.google.gson.JSonElement class represents an element of Json. We can use the toJsonTree() method of Gson class to serialize an object's representation as a tree of JsonElements. We can add/ insert an additional property to JSON string by using the getAsJsonObject() method of JSonElement. This method returns to get the element as JsonObject.

Syntax

public JsonObject getAsJsonObject()

Example

import com.google.gson.*;
public class AddPropertyGsonTest {
   public static void main(String[] args) {
      Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print JSON
      Student student = new Student("Adithya");
      String jsonStr = gson.toJson(student, Student.class);
      System.out.println("JSON String: \n" + jsonStr);
      JsonElement jsonElement = gson.toJsonTree(student);
      jsonElement.getAsJsonObject().addProperty("id", "115");
      jsonStr = gson.toJson(jsonElement);
      System.out.println("JSON String after inserting additional property: \n" + jsonStr);
   }
}
// Student class
class Student {
   private String name;
   public Student(String name) {
      this.name= name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Output

JSON String:
{
   "name": "Adithya"
}
JSON String after inserting additional property:
{
   "name": "Adithya",
   "id": "115"
}

Updated on: 19-Feb-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements