Home > Mobile >  Collect pairs key-value from JSONArrays in Java and return as one JSONArray
Collect pairs key-value from JSONArrays in Java and return as one JSONArray

Time:11-05

I have task with JSONObject, and exactly two JSONArray to retrieve some key and value values and return them as JSONArray:

the first JSONArray consists of two objects as below:

[{"name": "John", "id": "1"}, {"name": "Adam", "id": "2"}]

the second JSONArray consists of three objects (the one with id = 3 is omitted), where "id" is a link between two JSONArray:

[{"color:" red "," id ":" 1 "," country ":" Poland "}, {" color ":" green "," id ":" 2 "," country ":" Germany " }, {"color:" red "," id ":" 3 "," country ":" England "}]

and finally I would like to get JSONArray where we have two JSONObjects:

[{"color:" red "," name ":" John "," country ":" Poland "}, {" color ":" green "," name ":" Adam "," country ":" Germany " }]

Have any of you ever done similar things and would be able to get a tip?

Regards, Stan

Actually I tried create new JSONObject and next add to JSON Array, but I don't know how get only two JSONObject from second JSONArray and finally get expected result JSONArray.

CodePudding user response:

Assuming you are using the org.json classes JSONObject and JSONArray, something like this should work:

NOTE: it will only accept one value per key in the merged objects, if you want to merge values for the same key or pick a certain value for a key (if multiple exist) based on certain criteria, you will need additional logic

    JSONArray[] arraysToMerge = // array of your json arrays to merge on 'id'
    Map<String, JSONObject> merged = new HashMap<>();
    for (JSONArray array : arraysToMerge) {
      for (int i = 0; i < array.length(); i  ) {
        JSONObject obj = array.optJSONObject(i);
        if (obj != null) {
          String id = obj.optString("id");
          if (id != null) {
            JSONObject existingObj = merged.computeIfAbsent(id, (k) -> {
              obj.remove("id");
              return obj;
            });
            for (String name : JSONObject.getNames(obj)) {
              if (!name.equals("id")) {
                existingObj.put(name, obj.get(name));
              }
            }
          }
        }
      }
    }
    JSONArray mergedArray = new JSONArray(merged.values());

CodePudding user response:

Library Josson & Jossons has join operation.

https://github.com/octomix/josson

// Deserialization
Jossons jossons = new Jossons();
jossons.putDataset("array1",
    Josson.fromJsonString(
        "[{\"name\": \"John\", \"id\": \"1\"},"  
        " {\"name\": \"Adam\", \"id\": \"2\"}]"));
jossons.putDataset("array2",
    Josson.fromJsonString(
        "[{\"color\": \"red\", \"id\": \"1\", \"country\": \"Poland\"},"  
        " {\"color\": \"green\", \"id\": \"2\", \"country\": \"Germany\"},"  
        " {\"color\": \"red\", \"id\": \"3\", \"country\": \"England\"}]"));
// Left join
JsonNode node = jossons.evaluateQuery("array1{id} <=< array2{id}");
// Output
System.out.println(node.toPrettyString());
// Remove "id"
System.out.println(Josson.create(node).getNode("field(id:)").toPrettyString());

Output

[ {
  "name" : "John",
  "id" : "1",
  "color" : "red",
  "country" : "Poland"
}, {
  "name" : "Adam",
  "id" : "2",
  "color" : "green",
  "country" : "Germany"
} ]

Output after removed "id"

[ {
  "name" : "John",
  "color" : "red",
  "country" : "Poland"
}, {
  "name" : "Adam",
  "color" : "green",
  "country" : "Germany"
} ]
  • Related