Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Merging two json objects together with primary key

Lets say I have two arrays of JSONObjects in memory and each object has a key that is similar in both arrays:

Array 1

[
  {
    "name": "Big Melons Co.",
    "location": "Inner City Dubai"
    "id": "1A"
  },
  {
    "name": "Pear Flavored Juices Ltd",
    "location": "Seychelles"
    "id": "2A"
  },
  {
    "name": "Squeeze My Lemons LLC",
    "location": "UK"
    "id": "3A"
  }, {other JSON Objects...} ]

Array 2

[
  {
    "acceptsCard": "true"
    "id": "1A"
  },
  {
    "acceptsCard": "false"
    "id": "2A"
  },
  {
    "acceptsCard": "false"
    "id": "3A"
  }, {other JSON Objects...} ]

Now, I want to merge the two arrays together based on the primary key of "id" so they become one on my server side and then send the results back to my frontend - the resulting arraylist of objects should look like this:

MERGED ARRAY (Result)

  [
      {
        "name": "Great Juice Co.",
        "location": "Inner City Dubai"
        "acceptsCard": "true"
        "id": "1A"
      },
      {
        "name": "Pear Flavored Juices Ltd",
        "location": "Seychelles"
        "acceptsCard": "false"
        "id": "2A"
      },
      {
        "name": "Squeeze My Lemons LLC",
        "location": "UK"
        "acceptsCard": "false"
        "id": "3A"
      }, {other JSON Objects...} ]

How can I do this efficiently?

I can think of one highly inefficient way to do this (I'm dreading implementing this) - I would loop though each item in either array 1 or 2 and use the equal() method for the string in the "id" field to see whether the two matches. If they match, I would create a new JSONObject to contain both the fields from array 1 and 2.

like image 516
Simon Avatar asked Oct 19 '22 01:10

Simon


1 Answers

My Java is a little rusty but I would use a map.

List<JSONObject> objectsA = ... ;
List<JSONObject> objectsB = ... ;

Map entries = new HashMap<String, JSONObject>();
List<JSONObject> allObjects = new ArrayList<JSONObject>();
allObjects.addAll(objectsA);
allObjects.addAll(objectsB);

for (JSONObject obj: allObjects) {
    String key = obj.getString("id");
    JSONObject existing = entries.get(key);
    if (existing == null) {
        existing = new JSONObject();
        entries.put(key, existing);
    }

    for (String subKey : obj.keys()) {
        existing.put(subKey, obj.get(subKey));
    }
}

List<JSONObject> merged = entries.values();

This is more efficient than two nested loops and there's still room for improvement.

EDIT: References to external documentation and related answers.

  • http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
  • http://www.json.org/javadoc/org/json/JSONObject.html
  • https://stackoverflow.com/a/2403427/937006
like image 176
ctrlc-root Avatar answered Oct 27 '22 18:10

ctrlc-root