English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to add to JSON strings using Gson in Java/Insert other properties?

Content com.google.gson.JSonElementclass to represent the elementsJson. We can use Gsonof the toJsonTree()/By adding an additional attribute, the method serializes the representation of the object into a tree of JsonElements. We can addgetAsJsonObject()methodJSonElement. This method returns the element asJsonObjectObtained.

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: 
" + jsonStr);
      JsonElement jsonElement = gson.toJsonTree(student);
      jsonElement.getAsJsonObject().addProperty("id",  ""115");
      jsonStr = gson.toJson(jsonElement);
      System.out.println("JSON String after inserting additional property: 
" + 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 Result

JSON String:
{
   "name":  "Adithya"
}
JSON String after inserting additional property:
{
   "name":  "Adithya",
   "id":  ""115"
}
You Might Also Like