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

The 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.


public JsonObject getAsJsonObject()


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) { name;
   public String getName() {
      return name;
   public void setName(String name) { = name;


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