Skip to content
Advertisement

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!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement