Search code examples
jsonjava-8org.json

Json Array having multiple JsonObject Conversion to map based on java8


I have multiple apps which returns a JsonArray having multiple JsonObject like this e.g for app1

[ {"Server":"PCF","Port":"9878","Calls":"655"},
{"Server":"AWS","Port":"5672","Calls":"655"},.... ].

Fields in all the JsonObject are same. I want to create a map based on field Server which contains a list of JsonObject.

"PCF":[{"Server":"PCF","Port":"9878","Calls":"655"}, {"Server":"PCF","Port":"562","Calls":"65"}]

Conditions: 1) I want to use java8(I have done on older version). 2) I am using org.json.


Solution

  • I've not used the JSON-Java library before but from a little bit of research, seems to suggest that JsonArray from org.json implements java.lang.Iterable<java.lang.Object> therefore we could do:

    Map<String, List<JSONObject>> result = 
                StreamSupport.stream(jsonArray.spliterator(), false)
                             .map(f -> (JSONObject) f) // assumes every 'f' is a JSONObject otherwise use filter before map
                             .collect(groupingBy(f -> f.getString("Server")));
    

    if you don't cast to a JSONObject then this would return:

    Map<String, List<Object>> result =
                    StreamSupport.stream(jsonArray.spliterator(), false)
                                 .collect(groupingBy(f -> ((JSONObject)f).getString("Server")));
    

    imports:

    import java.util.stream.*;
    import static java.util.stream.Collectors.*;