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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22585970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:39:55  来源:igfitidea点击:

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

javajsongson

提问by curious1

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 HashMapto throw all data into it and then new Gson().toJson()?

这是可行的吗?我是否以正确的方式使用 GSON?或者我应该只使用 aHashMap将所有数据放入其中然后new Gson().toJson()

采纳答案by Simon Arsenault

You could do it this way:

你可以这样做:

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