英文:
How to convert Nested HashMap to Jettison JSONObject
问题
I have to convert a Map<String, Map<String, String>> to Codehaus-Jettison JSONObject.
I'm aware that using Gson and other libraries have easier ways of achieving this, but its a requirement hat Jettison be used in this case.
What I understand from the documentation is I could do:
Map<String, Map<String, String>> tagsMap = new HashMap<>();
Map<String, String> tags = new HashMap<>();
tags.put("tag1", "value1");
tags.put("tag2", "value2");
tags.put("tag3", "value3");
tagsMap.put("table1", tags);
tagsMap.put("table2", tags);
tagsMap.put("table3", tags);
JSONObject jsonObject = new JSONObject(tagsMap);
System.out.println(jsonObject.toString());
But the new JSONObject(map)
only seems to be working for Map<String, String> and for the above code I end up with this incorrect output:
{"table3":"{tag1=value1, tag2=value2, tag3=value3}","table2":"{tag1=value1, tag2=value2, tag3=value3}","table1":"{tag1=value1, tag2=value2, tag3=value3}"}
My desired output should be proper JSON content, like this:
{"table3":{"tag1":"value1", "tag2":"value2", "tag3":"value3"},"table2":{"tag1":"value1", "tag2":"value2", "tag3":"value3"},"table1":{"tag1":"value1", "tag2":"value2", "tag3":"value3"}}
Is there any way of doing this with at all ONLY Jettison?
英文:
I have to convert a Map<String, Map<String, String>> to Codehaus-Jettison JSONObject.
I'm aware that using Gson and other libraries have easier ways of achieving this, but its a requirement hat Jettison be used in this case.
What I understand from the documentation is I could do:
Map<String, Map<String, String>> tagsMap = new HashMap<>();
Map<String, String> tags = new HashMap<>();
tags.put("tag1", "value1");
tags.put("tag2", "value2");
tags.put("tag3", "value3");
tagsMap.put("table1", tags);
tagsMap.put("table2", tags);
tagsMap.put("table3", tags);
JSONObject jsonObject = new JSONObject(tagsMap);
System.out.println(jsonObject.toString());
But the new JSONObject(map)
only seems to be working for Map<String, String> and for the above code I end up with this incorrect output:
{"table3":"{tag1=value1, tag2=value2, tag3=value3}","table2":"{tag1=value1, tag2=value2, tag3=value3}","table1":"{tag1=value1, tag2=value2, tag3=value3}"}
My desired output should be proper JSON content, like this:
{"table3":{"tag1":"value1", "tag2":"value2", "tag3":"value3"},"table2":{"tag1":"value1", "tag2":"value2", "tag3":"value3"},"table1":{"tag1":"value1", "tag2":"value2", "tag3":"value3"}}
Is there any way of doing this with at all ONLY Jettison ?
答案1
得分: 1
似乎您正在使用较旧版本的 jettison,它在 jettison 版本 1.3 及更高版本上运行良好。升级库的版本,它将正常工作。
英文:
Seems you are using older version of jettison, its working fine on jettison version 1.3 and later. Upgrade the library version and it will work fine.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论