Sidharth Ramesh
Sidharth Ramesh

Reputation: 726

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 ?

Upvotes: 0

Views: 279

Answers (1)

Shahid Farooq
Shahid Farooq

Reputation: 104

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.

Upvotes: 1

Related Questions