com.google.gson.JSonElement 类表示的元素的Json。我们可以使用Gson 类的toJsonTree() 方法将对象的表示形式序列化为JsonElements的树。我们可以添加/通过插入一个附加属性,以JSON字符串getAsJsonObject()的方法JSonElement。返回此方法以将元素作为JsonObject获得。
public JsonObject getAsJsonObject()
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 classclass Student { private String name; public Student(String name) { this.name= name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
输出结果
JSON String: { "name": "Adithya" } JSON String after inserting additional property: { "name": "Adithya", "id": "115" }