tags:

views:

55

answers:

2

I have a string in an Android app that I am trying to convert into a JSON object. The string looks like this (except longer and with actual values instead of the dummy values I entered here):

[[{"1":"a"}],[{"1a":"1a","1b":"1b"},{"2a":"2a","2b":"2b"}]]

I have entered this exact string into two online JSON validators, and both of them confirm it to be valid JSON data. So I would assume that the JSONObject constructor would be able to accept this string and convert it into a JSON object. But when I try:

json = new JSONObject(result);

Where "result" is a String variable containing the string listed above, I get the following exception:

JSONException: A JSONObject text must begin with '{' at character 1 of [[{"1":"a"}],[{"1a":"1a","1b":"1b"},{"2a":"2a","2b":"2b"}]]

What's going on here? Is the JSONObject's parser broken?

+5  A: 

You are trying to create a JSONObject, but what you are actually giving it is a JSONArray. Did you try creating a JSONArray instead?

Alternatively, you could wrap your array in an object so that you can create a JSONObject out of it.

Mayra
Well, well. That was exactly the problem. Why didn't I see that? Thank you very much.
rnstewart
A: 

I would suggest using the GSon library instead as it appears to be more full-featured.
http://code.google.com/p/google-gson/
In addition, it may be helpful to use this tool to test your data (your data is valid btw): http://jsonformatter.curiousconcept.com/

Mondain