25

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!

2
  • My suggestion would have been to use some JSON-library for this, but does "solution in Java that doesn't require constructing Java Object representations of the JSON objects?" mean you don't want to use a separate library for whatever reason? Commented Oct 29, 2011 at 18:09
  • No, external libraries are fine - I'm sure they're necessary. I mean that I didn't want to make a Java Object for each object in the JSON array, i.e. I don't want to create MyObject myobj = new MyObject(name, car); for each object, then merge the arrays of MyObjects and convert the merged array back into JSON. I'd like to find a way to leave everything in JSON. Commented Oct 29, 2011 at 18:19

7 Answers 7

31

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();
Sign up to request clarification or add additional context in comments.

Comments

14

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.

4 Comments

Since I'm guaranteed to get back a valid JSON array of length > 0, doing as you suggest makes the most sense. Thanks!
I think that kind of hackery is dangerous and shouldn't be done. The api may later be improved to provide a better way of doing this but the fragile and unpexcted hack will waste more manminutes than processor time.
You're certainly entitled to your opinion, but I'd love to hear any concrete objection other than an appeal to general principles. Given the syntax of JSON and the parameters of this problem, the error checking mentioned above would be more than sufficient to render this quite robust. Treating this as a sting manipulation problem is many orders of magnitude more efficient for even moderate sized arrays, and I can think of multiple situations in which this solution would be preferable.
@Sojurn Dangerous how? I used this method and it works for me, I did make sure to check for null and empty json arrays.
5

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

Java version:

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;
}

Kotlin version:

fun mergeMultiJsonArray(vararg arrays: JSONArray): JSONArray {
    val outArr = JSONArray()
    for (array in arrays) 
        for (i in 0 until array.length())
            outArray.put(array.optJSONObject(i))
    return outArr
}

Comments

4

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);

1 Comment

If your JSON contains square brackets other than the ones used to declare the array then the code above will break. Use lastIndexOf instead of indexOf to prevent this from happening.
4

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;
}

Comments

2

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;
}

Comments

1

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");
}

2 Comments

what is "patches" here, inside the for loop?
i think it should be xyz. Thanks for the fix. This code works like a breeze.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.