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?

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 or even better than calling array.getJSONObject(0), use array.getJSONObject( index ); where index is >= 0 and < array length
Agreed Dorin. I kept it specific to his case in my example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.