2

I am trying to construct a JSONArray from a String, and extract the JSONObjects from inside it. Here is my code:

String jsonStr = "[{\"name\" : \"John Doe\",\"gender\":\"male\",\"age\":40},{\"name\" : \"Jane Doe\",\"gender\":\"female\",\"age\":30}]";

JSONArray jsonArr = new JSONArray(jsonStr);

I get the following error on the line JSONArray is declared:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code
        at org.json.JSONTokener.nextValue(JSONTokener.java:319)
        at org.json.JSONArray.<init>(JSONArray.java:119)
        at org.json.JSONArray.<init>(JSONArray.java:146)

I am thinking it should be possible to have an array of JSONObjects. Is there something wrong with the way I have constructed the string ? Any help is appreciated.

Thanks!

1
  • I get the same error, if the JSON source code is in a separate JAVA library project. I moved the source code for the JSON classes to the same project as the main/calling code and I no longer get the error? Commented Sep 5, 2012 at 21:37

2 Answers 2

2

You're missing the trailing ]

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

4 Comments

+1, but he's using java not javascript. single quotes are chars
Oh, good call. It wasn't tagged Java/Javascript, and I've always used JSON in JS, so I assumed JS heh. Is it possible to do it the other way round then, or will Java try and parse the keys as chars there? And totally totaly unrelated, but nice name :)
Sorry about the typo with the missing ]. I am getting the same error with it as well.
That's a good question, beyond my limited knowledge. I would assume it would error because double quotes are the standard for JSON.
2
 String jsonStr =" {\"array\": [{\"name\": \"John Doe\",\"gender\": \"male\",\"age\":40},{\"name\": \"Jane Doe\",\"gender\": \"female\",\"age\": 30 }]}";

this string is fine

if you want to validate any JSON syntax data this can help you

5 Comments

According to the docs, the string should start with [ and end with ]. If the code you posted works, it's probably worth submitting a bug report or whatever :)
Its funny how its possible to initialize a JSONObject from a String, but not a JSONArray of JSONObject.
Thanks Nammari, for the link. If I remove the escape character "\" from the string, JSONLint says its a valid JSON string.
if i answer you check my answer in the voting area :) this way how you can thank people in stackoverflow
I am new to stackoverflow. Apparently you need to garner 15 reputation points to vote up. Will do so as soon as I have them!

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.