0

I have this JSON string:

   [{"user_id":"123","email":"[email protected]","lat":"40.748329","lng":"-73.996223",
                    "first_name":"Alex","last_name":"Genadinik"}]

and this Java Code:

            try
            {
                JSONObject obj = new JSONObject(result);

                Log.d( "NAME: " , "test: " + obj.getString("first_name") );       

            }
            catch ( Exception e )
            {
                Log.d( "JSON ERRORZ: " , "some crap happened " + e.getMessage() );  
            }

But it throws this error:

[{"last_name":"Genadinik","first_name":"Alex","lng":"-73.996223","user_id":"1","email":"[email protected]","lat":"40.748329"}] of type org.json.JSONArray cannot be converted to JSONObject

Any idea how I can fix this and simply just extract the values in the JSON?

Thanks!

2 Answers 2

3

The error says it all. You're passing an array an it expects an object.

To fix your error you should remove the square brackets ([, ]) from your JSON string.

An object looks like:

{
    key: 'value'
}

Where as an array looks like:

[
    { key: 'value' },
    1,
    'some string'
]
Sign up to request clarification or add additional context in comments.

2 Comments

But if I use the JSONArray object, whats the function in there that gets me the value? I don't see anything applicable in the API - thanks!
You could use the getJSONObject(..) method :).
2

This JSON string is an array, not object, not the square brackets at the beginning (look here). Use JSONArray instead, and extract the JSONObjects from it.

3 Comments

But if I use the JSONArray object, whats the function in there that gets me the value? I don't see anything applicable in the API - thanks!
Would it be something like this: JSONArray obj = new JSONArray(result); JSONObject o = obj.getJSONObject(1); Log.d( "NAME: " , "test: " + o.getString("first_name") );
Yes. but start from index 0 :)]

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.