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

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

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.

Tags:

Java

Json