Java JsonObject 添加属性 - 地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22441134/
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
JsonObject add property - maps
提问by harsh
I have a class called Test with a String id
field and a HashMap map
like Map<String, String[]>
, Map<String, ArrayList<String>>
, and Map<String, HashMap>
(Here the second HashMap
is a <String, Integer>
one) I have the following code.
我有一个名为测试与类String id
字段和HashMap map
像 Map<String, String[]>
,Map<String, ArrayList<String>>
和Map<String, HashMap>
(这里第二个HashMap
是<String, Integer>
一个)我有下面的代码。
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", test.getId);
Like this, I want to add the Map to this. Adding like jsonObject.addProperty("map", String.valueOf(test.getMap()));
does not do the work properly as it add "(commas) to beginning and end. Can somebody tell me what is the correct way to do it?
像这样,我想将地图添加到此。添加 likejsonObject.addProperty("map", String.valueOf(test.getMap()));
并不能正常工作,因为它将“(逗号)添加到开头和结尾。有人能告诉我什么是正确的方法吗?
采纳答案by Sotirios Delimanolis
JsonObject
has add
method to add primitives, but only a single add
method to add complex types. This method expects a JsonElement
so that's what you have to create.
JsonObject
有add
添加基元的方法,但只有一个add
方法来添加复杂类型。此方法需要 aJsonElement
所以这就是您必须创建的。
JsonObject jsonObject = new JsonObject();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(test.getMap());
jsonObject.add("map", jsonElement);
I don't know exactly why you're doing this. In your last question, I showed you how to generate full JSON from the Test
class.
我不知道你为什么要这样做。在您的上一个问题中,我向您展示了如何从Test
类中生成完整的 JSON 。
You can use
您可以使用
gson.toJsonTree(test);
to get the JSON as a JsonElement
, which you can cast to a JsonObject
.
将 JSON 作为 a 获取JsonElement
,您可以将其强制转换为JsonObject
.