Search code examples
javajson-simple

parse json data already in an array?


I have the following data:

[{"class":"test","description":"o hai","example":"a","banana":"b"}]

As this JSON data is already in an array, I'm having troubles to parse this with JSON simple:

File file = new File( "/Users/FLX/test.json");
String s = FileUtils.readFileToString(file);

Object obj = parser.parse(s);
JSONArray array = (JSONArray) obj;
log.warn("WAAAAT"+array.get(1));

This doesn't work because "1" (description) is in array 0, which causes an out of bounds exception, how can I properly do this?


Solution

  • [] denotes an array, while {} denotes an object, so you have an array of objects.

    The way your JSON is formatted, you have an array which contains a single object. That single object has properties named "class", "description", "example", and "banana" with values "test", "o hai", "a", and "b" respectively.

    JSONArray is 0 based so array.get(1) would be out of bounds. In order to get description you would do something like array.getJSONObject(0).get("description")