I’m receiving an input of one or more Json arrays like
[{"operation":"buy", "unit-cost":10.00, "quantity": 10000},
{"operation":"sell", "unit-cost":20.00, "quantity": 5000}]
[{"operation":"buy", "unit-cost":20.00, "quantity": 10000},
{"operation":"sell", "unit-cost":10.00, "quantity": 5000}]
I tried to read the array using JSON-Java in this way:
JSONArray array = new JSONArray(json)
But this only reads the first array and ignores the second one.
How can I read multiple arrays from a Json String in Java?
I already tried with JSON-java and Jackson but I haven’t found the way to get the expected result.
2
Answers
You could evaluate the characters to determine when a complete array has been reached.
In this example, I’m ignoring the fact that a the brackets may occur within a text value.
This doesn’t appear to be the case with your data, so I’ve left out the check.
Output, for list.
I then used Gson to parse the data.
I’m using the SerializedName annotation here to conform the hyphenated name.
Additionally, I added a toString override to debug the output.
Here is a basic parse and output.
There is no automatic way to read it since the object is an appended array of objects. You’ll have to parse it yourself programmatically. Here is a possible way: