JsonObject添加属性 - 地图 [英] JsonObject add property - maps
问题描述
我有一个叫做Test的类,它有一个字符串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);
像这样,我想将Map添加到此处。添加如 jsonObject.addProperty(map,String.valueOf(test.getMap()));
不会正常工作,因为它将(逗号)添加到开头有人告诉我什么是正确的方法吗?
添加
方法来添加复杂类型。方法期望 JsonElement
,这就是你必须创建的。 JsonObject jsonObject = new JsonObject();
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(test.getMap());
jsonObject.add(map,jsonElement );
我不确切知道你为什么这样做,在你最后一个问题中,我向您展示了如何从 Test
类生成完整的JSON。您可以使用
gson.toJsonTree(test);
获取JSON JsonElement
,您可以将其转换为 JsonObject
。
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.
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?
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 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.
You can use
gson.toJsonTree(test);
to get the JSON as a JsonElement
, which you can cast to a JsonObject
.
这篇关于JsonObject添加属性 - 地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!