Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 231
Paul Avatar asked Oct 29 '11 18:10

Paul


2 Answers

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(); 
like image 112
Brian Klug Avatar answered Oct 10 '22 19:10

Brian Klug


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.

like image 27
Ernest Friedman-Hill Avatar answered Oct 10 '22 19:10

Ernest Friedman-Hill