Reputation: 85
assuming I have the following HashMap that needed to be converted into JSON:
HashMap <String, String> test1 = {k1,v1},{k2,v2},{k3,v3},{k4,v4};
I am aware of using JSONObject to create the JSON output:
JSONObject json = new JSONObject ( test1 );
However, the json will be in the following format:
{"k1":"v1","k2":"v2","k3":"v3","k4":"v4"}
I would like for the output to be something like this:
[{"key":"k1","value":"v1"},
{"key":"k2","value":"v2"},
{"key":"k3","value":"v3"},
{"key":"k4","value":"v4"}]
Does anyone have input on how to convert to formatted JSON? Further question: what if the HashMap's key are Set of String?
HashMap <String, Set<String>> test1 = {k1,{v1,v2,v3}},{k2,{v4,v5,v6}},{k3,{v7,v8,v9}};
I would like for the output to be something like this:
[{"key":"k1","value":["v1","v2","v3"]},
{"key":"k2","value":["v4","v5","v6"]},
{"key":"k3","value":["v7","v8","v9"]}]
Thanks for the help
Upvotes: 1
Views: 278
Reputation: 44960
Assuming you are working with json-simple library you could transform each map entry into a new JSONObject
first and then add all of them into a JSONArray
:
Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3", "k4", "v4");
JSONArray arr = map.entrySet().stream()
.map(e -> Map.of("key", e.getKey(), "value", e.getValue()))
.map(JSONObject::new)
.collect(JSONArray::new, JSONArray::add, JSONArray::addAll);
System.out.println(arr);
will print:
[{"value":"v4","key":"k4"},{"value":"v3","key":"k3"},{"value":"v2","key":"k2"},{"value":"v1","key":"k1"}]
the order of elements in the output JSONArray
will depend on the map used, you need LinkedHashMap
if you want to preserve the insertion order when iterating. Otherwise you must order the stream with a comparator.
Upvotes: 2