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"
}
]
}
}
]
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.