How to add an object as a property of a JsonObject object?

不问归期 提交于 2021-02-08 12:19:35

问题


Here is what I am doing:

JsonObject jobj = new JsonObject();
jobj.addProperty("name", "great car");

I am hoping to add another property whose value is an object as follows:

jobj.addProperty("car", A_CAR_OBJECT);

But it appears that GSON does not allow me to do jobj.addProperty("car", A_CAR_OBJECT). I am going to eventually do the following:

String json = new Gson().toJson(jobj);

to get the Json string.

Is this doable? Am I using GSON the right way? Or should I just use a HashMap to throw all data into it and then new Gson().toJson()?


回答1:


You could do it this way:

jobj.add("car", new Gson().toJsonTree(A_CAR_OBJECT));


来源:https://stackoverflow.com/questions/22585970/how-to-add-an-object-as-a-property-of-a-jsonobject-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!