1

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?

DVK
  • 126,886
  • 32
  • 213
  • 327
FLX
  • 4,634
  • 14
  • 47
  • 60

1 Answers1

2

[] 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")

digitaljoel
  • 26,265
  • 15
  • 89
  • 115
  • +1 or even better than calling array.getJSONObject(0), use array.getJSONObject( index ); where index is >= 0 and < array length –  Feb 14 '12 at 16:37
  • Agreed Dorin. I kept it specific to his case in my example. – digitaljoel Feb 14 '12 at 16:38