JsonObject add property - maps

大城市里の小女人 提交于 2019-12-24 04:04:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/22441134/jsonobject-add-property-maps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!