1

I'm new to Spring Boot and json so forgive me if a silly question. I'm trying to read in my json file, convert it to a JSONObject, then convert this to a JSONArray. I've commented out the two lines which do this as I tried going from reading the file to the Array instead. My JSON file starts with a [ so I'm unsure why I get this error.

Exception in thread "main" org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]

InputStream inputStream = TypeReference.class.getResourceAsStream("/json/req.json");        
List<PIECase> allCases = new ArrayList<PIECase>();              
InputStream rawJson = inputStream;
//JSONObject jsonObject = new JSONObject(rawJson);
//JSONArray jsonArray = jsonObject.getJSONArray("PIECases");
JSONArray jsonArray = new JSONArray(rawJson.toString());

for(int i =0; i < jsonArray.length(); i++) {
    //the JSON data we get back from array as a json object
    JSONObject jsonPIECases = jsonArray.getJSONObject(i);

    // more code
}

req.json

[
    {
        "PIECases": {
            "PIECases": [
                {
                    "Case_ID": "1",
                    "SortCode": "123456",
                    "AccountNumber": "12345678",
                    "Amount": "50",
                    "DateOfPayment": "2019-07-29"
                },
                {
                    "Case_ID": "2",
                    "SortCode": "123456",
                    "AccountNumber": "12345678",
                    "Amount": "50",
                    "DateOfPayment": "2019-07-29"
                }
            ]
        }
    }
]
buræquete
  • 14,226
  • 4
  • 44
  • 89
Coder
  • 197
  • 1
  • 17
  • 1
    Similar question to - https://stackoverflow.com/questions/39979590/a-jsonarray-text-must-start-with-at-1-character-2-line-1 - https://stackoverflow.com/questions/27517649/org-json-jsonexception-a-jsonarray-text-must-start-with - https://stackoverflow.com/questions/9854678/parssing-jsonexception-a-jsonarray-text-must-start-with-at-character-1 – suntzu Aug 02 '19 at 16:20
  • Include your stack trace – Coder Aug 02 '19 at 16:23
  • Note that Spring Boot will include transparent JSON support out of the box, so you don't need to do any of this, just define Java classes mapping your data and use them as method parameters. – chrylis -cautiouslyoptimistic- Aug 02 '19 at 16:45

1 Answers1

1

rawJson.toString() does not return the json content but just the result of default Object#toString() method of the InputStream, use;

JsonReader jsonReader = Json.createReader(inputStream);
JsonArray array = jsonReader.readArray();
jsonReader.close();

from JsonArray

buræquete
  • 14,226
  • 4
  • 44
  • 89