How to convert Nested HashMap to Jettison JSONObject

211 views Asked by At

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

There are 1 answers

0
Shahid Farooq On BEST ANSWER

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.