0

I am working with restful webservice and I get json from it like the following

  response = [{"id":1,"name":"Appetizers","image":"iVBORw0KGgoAAAANSUhEUgAAADgAAAAkCAIAAABT8G6pAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABb5SURBVFhHPVgHUFPrtmbevTPvvnPvO8eKKJ1ASAikEEIaSYBAEkroSLWBHex67A3FBhYsWEFUBBuCDRRRpCMlhPS+0zs1gHD0HN72vjfvnzV/dpI9s7 ....

after that I want to convert this json to JSONObject

  JSONObject obj = new JSONObject(response);

and when I execute this command I get the follwoing error

org.json.JSONException: Value [{"resturantID":{"phoneNo":"a","id":1,"fax":"a","address":"a" ...

my program was working good when I was using glassfish 3 because the json structure was different from this what is the problem ?

1
  • 1
    here the "response" string is not JSONObject. It is JSONArray. You first need to get the JSONArray and from that you need to fetch all the JSONObjects Commented Jul 12, 2013 at 7:56

3 Answers 3

1

if your response hold the output of the stringbuilder after iterations then you can try below code

try{
            jArray = new JSONArray(response);
            for(int i=0;i<jArray.length();i++){
                    json_data = jArray.getJSONObject(i);
            }
}

NOTE:do not forget to declare jArray(object of JSONARRAY) and json_data(object of JSONOBJECT) at class level

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

Comments

1

This is a JSONArray and not a JSONObject - to make a JSONObject from it, use

JSONObject jsonObject = jsonArray.getJSONObject(0);

this gets the first JSONObject from this JSONArray.

If you have multiple JSONObjects, use this:

JSONObject jsonObject;
for(int n = 0; n < jsonArray.length(); n++)
{
    jsonObject = jsonArray.getJSONObject(n);
}

Comments

0

I think, problem is on your JSON. JSON is not valid.

"id":1

it should be

"id":"1"

Please check.

1 Comment

this actually is valid, it´s just an int instead of a String

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.