0

I'm triyng to convert json in string format to a JSONObject.

My json (received from my server) is like

[{ "key": "value", "key2": "value2"}, { "key": "value2", "key2": "value3"}]

And i have tried

 JSONObject obj = new JSONObject(json);

But obj is always null and my json is in a valid format (tested on http://jsonlint.com/)

Do I have to do smthing on my String first ?

Thanks,

1

1 Answer 1

3

You are trying to parse a JSONArray to JSONOject.

Do this

JSONArray obj = new JSONArray(json);

A thumb rule: If JSON string starts with [, its an array and if it starts with { then its an object.

This is how you should parse it.

JSONArray obj = new JSONArray(json);
for(int i = 0; i < obj.length(); i++)
{
    JSONObject temp = obj.get(i);
    Log.d("Json parsing", "key: " + temp.optString("key"));
    Log.d("Json parsing", "key2: " + temp.optString("key2"));
}

Output will be

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

Comments

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.