Java: Merging two json objects together with primary key

半腔热情 提交于 2019-12-07 07:37:17

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/32850554/java-merging-two-json-objects-together-with-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!