简体   繁体   中英

In Java, how can I combine two JSON arrays of objects?

I have several string each containing a JSON representation of an array of objects. Here's an example in code to illustrate, though this is not my actual code (the JSON strings are passed in):

String s1 = "[{name: "Bob", car: "Ford"},{name: "Mary", car: "Fiat"}]";
String s2 = "[{name: "Mack", car: "VW"},{name: "Steve", car: "Mercedes Benz"}]";

I need to combine those two JSON arrays into one large JSON array. I could treat this as a String manipulation problem and replace the inner end square brackets with commas but that's not particularly robust (though I am guaranteed to get valid JSON).

I'd rather treat these two Strings as JSON arrays and just add them together somehow. It's a great plan except I don't know the "somehow" part.

Does anyone know a solution in Java that doesn't require constructing Java Object representations of the JSON objects?

Thanks!

This code will take sourceArray (s2), and append it to the end of destinationArray (s1):

String s1 = "[{name: \"Bob\", car: \"Ford\"},{name: \"Mary\", car: \"Fiat\"}]";
String s2 = "[{name: \"Mack\", car: \"VW\"},{name: \"Steve\", car: \"Mercedes Benz\"}]";

JSONArray sourceArray = new JSONArray(s2);
JSONArray destinationArray = new JSONArray(s1);

for (int i = 0; i < sourceArray.length(); i++) {
    destinationArray.put(sourceArray.getJSONObject(i));
}

String s3 = destinationArray.toString();

You really have only two choices: parse the JSON (which invariably would involve constructing the objects) or don't parse the JSON. Not parsing is going to be cheaper, of course.

At first glance your idea about treating it as a String-manipulation problem might sound fragile, but the more I think about it, the more it seems to make fine sense. For error detection you could easily confirm that you were really dealing with arrays by checking for the square brackets; after that, just stripping off the ending bracket, adding a comma, stripping off the beginning bracket, and adding the "tail" should work flawlessly. The only exception I can think of is if either array is empty, you should just return the other String unchanged; again, that's very easy to check for as a String.

I really don't think there's any reason to make it more complex than that.

I used this code for Combine two Json Array.

String s1 = "[{name: \"Bob\", car: \"Ford\"},{name: \"Mary\", car: \"Fiat\"}]";
String s2 = "[{name: \"Mack\", car: \"VW\"},{name: \"Steve\", car: \"Mercedes Benz\"}]";
String s3=new String("");
s1=s1.substring(s1.indexOf("[")+1, s1.lastIndexOf("]"));
s2=s2.substring(s2.indexOf("[")+1, s2.lastIndexOf("]"));
s3="["+s1+","+s2+"]";
System.out.println(s3);

And here is my solution, You may want to merge more than two arrays :

public static JSONArray mergeMultiJsonArray(JSONArray... arrays) {
    JSONArray outArray = new JSONArray();
    for (JSONArray array : arrays)
        for (int i = 0; i < array.length(); i++)
            outArray.put(array.optJSONObject(i));
    return outArray;
}

i use this code to append all the elements of a jsonArray to a common JsonArray.

public JSONArray getMergeJsonArrays(ArrayList<JSONArray> jsonArrays) throws JSONException
{
    JSONArray MergedJsonArrays= new JSONArray();
     for(JSONArray tmpArray:jsonArrays)
     {
        for(int i=0;i<tmpArray.length();i++)
        {
            MergedJsonArrays.put(tmpArray.get(i));
        }
     }
    return MergedJsonArrays;
}

This function does the magic, adding multiples arrays returning one JSONArray with all elements

public static JSONArray JoinArrays(JSONArray... jsonArrays) {
    JSONArray resultJSONArray = new JSONArray();
    Arrays.stream(jsonArrays).forEach(jsonArray -> IntStream.range(0, jsonArray.length()).mapToObj(jsonArray::get).forEach(resultJSONArray::put));
    return resultJSONArray;
}

Use Below Method pass all JSON array in ArrayList this method will return cumulative JsonArray

public JSONArray getMergeJson(ArrayList<JSONArray> xyz){
    JSONArray result=null;
    JSONObject obj= new JSONObject();
    obj.put("key",result);
    for(JSONArray tmp:patches){
        for(int i=0;i<tmp.length();i++){
         obj.append("key", tmp.getJSONObject(i));   ;
        }

            }
    return obj.getJSONArray("key");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM