合并(Concat)Java中的多个JSONObjects

时间:2010-03-08 17:12:24

标签: java json concat

我从两个不同的来源消耗了一些JSON,我最终得到了两个JSONObject,我想将它们组合成一个。

数据:

"Object1": {
    "Stringkey":"StringVal",
    "ArrayKey": [Data0, Data1]
}

"Object2": {
    "Stringkey":"StringVal",
    "Stringkey":"StringVal",
    "Stringkey":"StringVal",
}

代码,使用http://json.org/java/库:

// jso1 and jso2 are some JSONObjects already instantiated
JSONObject Obj1 = (JSONObject) jso.get("Object1");
JSONObject Obj2 = (JSONObject) jso.get("Object2");

因此,在这种情况下,我想要将Obj1Obj2结合起来,以便为另一个创建一个全新的JSONObject或concat。除了将它们分开并单独添加put s之外的任何想法?

15 个答案:

答案 0 :(得分:48)

如果你想要一个带有两个键的对象,Object1和Object2,你可以这样做:

JSONObject Obj1 = (JSONObject) jso1.get("Object1");
JSONObject Obj2 = (JSONObject) jso2.get("Object2");
JSONObject combined = new JSONObject();
combined.put("Object1", Obj1);
combined.put("Object2", Obj2);

如果你想合并它们,那么例如顶级对象有5个键(Stringkey1,ArrayKey,StringKey2,StringKey3,StringKey4),我认为你必须手动执行:

JSONObject merged = new JSONObject(Obj1, JSONObject.getNames(Obj1));
for(String key : JSONObject.getNames(Obj2))
{
  merged.put(key, Obj2.get(key));
}

如果JSONObject实现Map并且支持putAll,这将会容易得多。

答案 1 :(得分:21)

您可以像这样创建一个新的JSONObject:

JSONObject merged = new JSONObject();
JSONObject[] objs = new JSONObject[] { Obj1, Obj2 };
for (JSONObject obj : objs) {
    Iterator it = obj.keys();
    while (it.hasNext()) {
        String key = (String)it.next();
        merged.put(key, obj.get(key));
    }
}

使用此代码,如果Obj1Obj2之间有任何重复的密钥,Obj2中的值将保留。如果您希望保留Obj1中的值,则应该反转第2行中数组的顺序。

答案 2 :(得分:19)

在某些情况下,您需要深度合并,即合并具有相同名称的字段内容(就像在Windows中复制文件夹时一样)。此功能可能会有所帮助:

/**
 * Merge "source" into "target". If fields have equal name, merge them recursively.
 * @return the merged object (target).
 */
public static JSONObject deepMerge(JSONObject source, JSONObject target) throws JSONException {
    for (String key: JSONObject.getNames(source)) {
            Object value = source.get(key);
            if (!target.has(key)) {
                // new value for "key":
                target.put(key, value);
            } else {
                // existing value for "key" - recursively deep merge:
                if (value instanceof JSONObject) {
                    JSONObject valueJson = (JSONObject)value;
                    deepMerge(valueJson, target.getJSONObject(key));
                } else {
                    target.put(key, value);
                }
            }
    }
    return target;
}



/**
 * demo program
 */
public static void main(String[] args) throws JSONException {
    JSONObject a = new JSONObject("{offer: {issue1: value1}, accept: true}");
    JSONObject b = new JSONObject("{offer: {issue2: value2}, reject: false}");
    System.out.println(a+ " + " + b+" = "+JsonUtils.deepMerge(a,b));
    // prints:
    // {"accept":true,"offer":{"issue1":"value1"}} + {"reject":false,"offer":{"issue2":"value2"}} = {"reject":false,"accept":true,"offer":{"issue1":"value1","issue2":"value2"}}
}

答案 3 :(得分:3)

这个包装器方法将有所帮助:

private static JSONObject merge(JSONObject... jsonObjects) throws JSONException {

    JSONObject jsonObject = new JSONObject();

    for(JSONObject temp : jsonObjects){
        Iterator<String> keys = temp.keys();
        while(keys.hasNext()){
            String key = keys.next();
            jsonObject.put(key, temp.get(key));
        }

    }
    return jsonObject;
}

答案 4 :(得分:2)

合并任意数量的JSONObjects的现成方法:

/**
 * Merges given JSONObjects. Values for identical key names are merged 
 * if they are objects, otherwise replaced by the latest occurence.
 *
 * @param jsons JSONObjects to merge.
 *
 * @return Merged JSONObject.
 */
public static JSONObject merge(
  JSONObject[] jsons) {

  JSONObject merged = new JSONObject();
  Object parameter;

  for (JSONObject added : jsons) {

    for (String key : toStringArrayList(added.names())) {
      try {

        parameter = added.get(key);

        if (merged.has(key)) {
          // Duplicate key found:
          if (added.get(key) instanceof JSONObject) {
            // Object - allowed to merge:
            parameter =
              merge(
                new JSONObject[]{
                  (JSONObject) merged.get(key),
                  (JSONObject) added.get(key)});
          }
        }

        // Add or update value on duplicate key:
        merged.put(
          key,
          parameter);

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }

  }

  return merged;
}

/**
 * Convert JSONArray to ArrayList<String>.
 *
 * @param jsonArray Source JSONArray.
 *
 * @return Target ArrayList<String>.
 */
public static ArrayList<String> toStringArrayList(JSONArray jsonArray) {

  ArrayList<String> stringArray = new ArrayList<String>();
  int arrayIndex;

  for (
    arrayIndex = 0;
    arrayIndex < jsonArray.length();
    arrayIndex++) {

    try {
      stringArray.add(
        jsonArray.getString(arrayIndex));
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  return stringArray;
}

答案 5 :(得分:1)

感谢Erel。这是Gson版本。

/**
 * Merge "source" into "target". If fields have equal name, merge them recursively.
 * Null values in source will remove the field from the target.
 * Override target values with source values
 * Keys not supplied in source will remain unchanged in target
 * 
 * @return the merged object (target).
 */
public static JsonObject deepMerge(JsonObject source, JsonObject target) throws Exception {

    for (Map.Entry<String,JsonElement> sourceEntry : source.entrySet()) {
        String key = sourceEntry.getKey();
        JsonElement value = sourceEntry.getValue();
        if (!target.has(key)) {
            //target does not have the same key, so perhaps it should be added to target
            if (!value.isJsonNull()) //well, only add if the source value is not null
            target.add(key, value);
        } else {
            if (!value.isJsonNull()) {
                if (value.isJsonObject()) {
                    //source value is json object, start deep merge
                    deepMerge(value.getAsJsonObject(), target.get(key).getAsJsonObject());
                } else {
                    target.add(key,value);
                }
            } else {
                target.remove(key);
            }
        }
    }
    return target;
}



/**
 * simple test
 */
public static void main(String[] args) throws Exception {
    JsonParser parser = new JsonParser();
    JsonObject a = null;
    JsonObject b = null;
    a = parser.parse("{offer: {issue1: null, issue2: null}, accept: true, reject: null}").getAsJsonObject();
    b = parser.parse("{offer: {issue2: value2}, reject: false}").getAsJsonObject();
    System.out.println(deepMerge(a,b));
    // prints:
    // {"offer":{},"accept":true}
    a = parser.parse("{offer: {issue1: value1}, accept: true, reject: null}").getAsJsonObject();
    b = parser.parse("{offer: {issue2: value2}, reject: false}").getAsJsonObject();
    System.out.println(deepMerge(a,b));
    // prints:
    // {"offer":{"issue2":"value2","issue1":"value1"},"accept":true}

}

答案 6 :(得分:0)

除了@ erel的答案之外,我还必须对外org.json.simple进行此编辑(我使用else)来处理JSONArray

            // existing value for "key" - recursively deep merge:
            if (value instanceof JSONObject) {
                JSONObject valueJson = (JSONObject)value;
                deepMerge(valueJson, (JSONObject) target.get(key));
            } 

            // insert each JSONArray's JSONObject in place
            if (value instanceof JSONArray) {
                ((JSONArray) value).forEach(
                    jsonobj ->
                    ((JSONArray) target.get(key)).add(jsonobj));
            }
            else {
                target.put(key, value);
            }

答案 7 :(得分:0)

我使用string将新对象连接到现有对象。

private static void concatJSON() throws IOException, InterruptedException {

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(new File(Main.class.getResource("/file/user.json").toURI())));


    JSONObject jsonObj = (JSONObject) obj; //usernameJsonObj

    String [] values = {"0.9" , Date.from(Calendar.getInstance().toInstant()).toLocaleString()},
            innermost = {"Accomplished", "LatestDate"}, 
            inner = {"Lesson1", "Lesson2", "Lesson3", "Lesson4"};
    String in = "Jayvee Villa";

    JSONObject jo1 = new JSONObject();
    for (int i = 0; i < innermost.length; i++)
        jo1.put(innermost[i], values[i]);

    JSONObject jo2 = new JSONObject();
    for (int i = 0; i < inner.length; i++)
        jo2.put(inner[i], jo1);

    JSONObject jo3 = new JSONObject();
    jo3.put(in, jo2);

    String merger = jsonObj.toString().substring(0, jsonObj.toString().length()-1) + "," +jo3.toString().substring(1);

    System.out.println(merger);
    FileWriter pr = new FileWriter(file);
    pr.write(merger);
    pr.flush();
    pr.close();
}

答案 8 :(得分:0)

对于我来说,该功能有效:

private static JSONObject concatJSONS(JSONObject json, JSONObject obj) {
    JSONObject result = new JSONObject();

    for(Object key: json.keySet()) {
        System.out.println("adding " + key + " to result json");
        result.put(key, json.get(key));
    }

    for(Object key: obj.keySet()) {
        System.out.println("adding " + key + " to result json");
        result.put(key, obj.get(key));
    }

    return result;
}

(注意)-json的concataion的此实现用于导入 org.json.simple.JSONObject;

答案 9 :(得分:0)

合并类型化的数据结构树并非易事,您需要定义优先级,处理不兼容的类型,定义如何将其强制转换和合并...

因此,我认为您不会避免

  

...将它们全部拉开,然后通过看跌期权分别添加。

如果您的问题是:有人为我做了吗? 然后,我想您可以看看我复活的YAML merging library/tool。 (YAML是JSON的超集),并且这些原理对两者都适用。
(但是,此特定代码返回YAML对象,而不是JSON。请随意扩展项目并发送PR。)

答案 10 :(得分:0)

今天,我也在努力合并JSON对象,并提供了以下解决方案(使用Gson库)。

private JsonObject mergeJsons(List<JsonObject> jsonObjs) {
    JsonObject mergedJson = new JsonObject();
    jsonObjs.forEach((JsonObject jsonObj) -> {
        Set<Map.Entry<String, JsonElement>> entrySet = jsonObj.entrySet();
        entrySet.forEach((next) -> {
            mergedJson.add(next.getKey(), next.getValue());
        });
    });
    return mergedJson;
}

答案 11 :(得分:0)

上面已经有人提到过。我将发布一个简短的版本。

要合并两个JSONObject json1json2,您可以像这样简单地用String处理它:

String merged = json1.toString().substring(0, json1.length() - 1) + "," +
json2.toString().substring(1);
JSONObject mergedJson = new JSONObject(merged);

当然,不要忘记处理JSONException。 :)  希望对您有帮助。

答案 12 :(得分:0)

这就是我要做的

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * This class has all static functions to merge 2 objects into one
 */
public class MergeHelper {
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * return a merge JsonNode, merge newJson into oldJson; override or insert
     * fields from newJson into oldJson
     * 
     * @param oldJson
     * @param newJson
     * @return
     */
    public static JsonNode mergeJsonObject(JsonNode oldJson, JsonNode newJson) {
        ObjectNode merged = objectMapper.createObjectNode();
        merged.setAll((ObjectNode) oldJson);
        merged.setAll((ObjectNode) newJson);
        return merged;
    }
}

答案 13 :(得分:0)

An improved version of merge on Gson's JsonObjects - can go any level of nested structure
 /**
 * Merge "source" into "target". 
 * 
 * <pre>
 *     An improved version of merge on Gson's JsonObjects - can go any level of nested structure:
 *             1. merge root & nested attributes.
 *             2. replace list of strings. For. eg.
 *              source -> "listOfStrings": ["A!"]
 *              dest -> "listOfStrings": ["A", "B"]
 *              merged -> "listOfStrings": ["A!", "B"]
 *             3. can merge nested objects inside list. For. eg.
 *              source -> "listOfObjects": [{"key2": "B"}]
 *              dest -> "listOfObjects": [{"key1": "A"}]
 *              merged -> "listOfObjects": [{"key1": "A"}, {"key2": "B"}]
 * </pre>
 * @return the merged object (target).
 */
public static JsonObject deepMerge(JsonObject source, JsonObject target) {
    for (String key: source.keySet()) {
        JsonElement srcValue = source.get(key);
        if (!target.has(key)) {
            target.add(key, srcValue);
        } else {
            if (srcValue instanceof JsonArray) {
                JsonArray srcArray = (JsonArray)srcValue;
                JsonArray destArray = target.getAsJsonArray(key);
                if (destArray == null || destArray.size() == 0) {
                    target.add(key, srcArray);
                    continue;
                } else {
                    IntStream.range(0, srcArray.size()).forEach(index -> {
                        JsonElement srcElem = srcArray.get(index);
                        JsonElement destElem = null;
                        if (index < destArray.size()) {
                            destElem = destArray.get(index);
                        }
                        if (srcElem instanceof JsonObject) {
                            if (destElem == null) {
                                destElem = new JsonObject();
                            }
                            deepMerge((JsonObject) srcElem, (JsonObject) destElem);
                        } else {
                            destArray.set(index, srcElem);
                        }
                    });
                }
            } else if (srcValue instanceof JsonObject) {
                JsonObject valueJson = (JsonObject)srcValue;
                deepMerge(valueJson, target.getAsJsonObject(key));
            } else {
                target.add(key, srcValue);
            }
        }
    }
    return target;
}

答案 14 :(得分:0)

距离问题还有一段时间,但是现在JSONObject实现了“ toMap”方法,因此您可以尝试以下方式:

Map<String, Object> map = Obj1.toMap();      //making an HashMap from obj1
map.putAll(Obj2.toMap());                    //moving all the stuff from obj2 to map
JSONObject combined = new JSONObject( map ); //new json from map