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

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

JsonObject add property - maps

javajsongson

提问by harsh

I have a class called Test with a String idfield and a HashMap maplike Map<String, String[]>, Map<String, ArrayList<String>>, and Map<String, HashMap>(Here the second HashMapis a <String, Integer>one) I have the following code.

我有一个名为测试与类String id字段和HashMap mapMap<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

JsonObjecthas addmethod to add primitives, but only a single addmethod to add complex types. This method expects a JsonElementso that's what you have to create.

JsonObjectadd添加基元的方法,但只有一个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 Testclass.

我不知道你为什么要这样做。在您的上一个问题中,我向您展示了如何从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.