如何将对象添加为JsonObject对象的属性?

时间:2021-01-16 19:34:25

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:

但似乎GSON不允许我做jobj.addProperty(“car”,A_CAR_OBJECT)。我最终会做以下事情:

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

to get the Json string.

得到Json字符串。

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()?

这可行吗?我是否正确使用GSON?或者我应该只使用HashMap将所有数据抛入其中,然后使用新的Gson()。toJson()?

1 个解决方案

#1


21  

You could do it this way:

你可以这样做:

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

#1


21  

You could do it this way:

你可以这样做:

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