skip to Main Content

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


  1. "I’m receiving an input of one or more Json arrays …
    … How can I read multiple arrays from a Json String in Java? …"

    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.

    String string =
        "[{"operation":"buy", "unit-cost":10.00, "quantity": 10000},n" +
        "{"operation":"sell", "unit-cost":20.00, "quantity": 5000}]n" +
        "[{"operation":"buy", "unit-cost":20.00, "quantity": 10000},n" +
        "{"operation":"sell", "unit-cost":10.00, "quantity": 5000}]";
    List<String> list = new ArrayList<>();
    int index = 0, offset = 0, count = 0;
    for (char character : string.toCharArray()) {
        switch (character) {
            case '[' -> count++;
            case ']' -> {
                count--;
                if (count == 0) {
                    list.add(string.substring(offset, index + 1).strip());
                    offset = index + 1;
                }
            }
        }
        index++;
    }
    

    Output, for list.

    0 = '[{"operation":"buy", "unit-cost":10.00, "quantity": 10000},
    {"operation":"sell", "unit-cost":20.00, "quantity": 5000}]'
    1 = '[{"operation":"buy", "unit-cost":20.00, "quantity": 10000},
    {"operation":"sell", "unit-cost":10.00, "quantity": 5000}]'
    

    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.

    class Data {
        String operation;
        @SerializedName("unit-cost") float unitCost;
        float quantity;
    
        @Override
        public String toString() {
            return "{operation= '%s', ".formatted(operation)
                + "unitCost= %s, ".formatted(unitCost)
                + "quantity= %s}".formatted(quantity);
        }
    }
    

    Here is a basic parse and output.

    Gson gson = new Gson();
    List<Data[]> data = new ArrayList<>();
    for (String value : list)
        data.add(gson.fromJson(value, Data[].class));
    
    for (Data[] datum : data)
        System.out.println(Arrays.toString(datum));
    
    [{operation= 'buy', unitCost= 10.0, quantity= 10000.0}, {operation= 'sell', unitCost= 20.0, quantity= 5000.0}]
    [{operation= 'buy', unitCost= 20.0, quantity= 10000.0}, {operation= 'sell', unitCost= 10.0, quantity= 5000.0}]
    
    Login or Signup to reply.
  2. 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:

    import java.util.ArrayList;
    import org.json.*;
    
    public class JsonTest {
    
        public static final void main(String... args){
            String str = "[{"operation":"buy", "unit-cost":10.00, "quantity": 10000},n" +
                            "{"operation":"sell", "unit-cost":20.00, "quantity": 5000}]n" +
                            "[{"operation":"buy", "unit-cost":20.00, "quantity": 10000},n" +
                            "{"operation":"sell", "unit-cost":10.00, "quantity": 5000}]";
    
            // store all the arrays in a list
            ArrayList<JSONArray> jsonArrays = new ArrayList<>();
            
            int last, beg = last = 0;
            while(true){
                // substring up to ] and treat it as a json array
                last = str.indexOf("]", beg);
                if(last == -1) break;
                JSONArray arr = new JSONArray(str.substring(beg, last+1));
                jsonArrays.add(arr);
                beg = last+1;
            }
            
            // print all the json objects in the array list
            for(JSONArray arr : jsonArrays){
                for(int i = 0; i < arr.length(); i++){
                    JSONObject obj = arr.getJSONObject(i);
                    System.out.println(obj.toString());
                }
            }
    
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search