53

Possible Duplicate:
JSON Array iteration in Android/Java

I am fetching JSON string from server and I have already got JSON string by code. But I didn't understand how to parse it.

Below is my JSON string

{
    "university": {
        "name": "oxford",
        "url": "http://www.youtube.com"
    },
    "1": {
        "id": "2",
        "title": "Baseball",
        "datetime": "2011-11-11 10:41:46"
    },
    "2": {
        "id": "1",
        "title": "Two basketball team players earn all state honors",
        "datetime": "2011-11-11 10:40:57"
    }
}

Please provide any guidance or code snippet.

0

2 Answers 2

125

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....
Sign up to request clarification or add additional context in comments.

5 Comments

can we get how many objects in json string
Yes you can simply use "mainObject.length();"
Edited to use getString() instead of getJSONObject() when getting String values. Using getJSONObject() caused a JSONException when I ran similar code that was fixed by using getString().
getString(), not getJsonString() as is written in the example, right?
Right @de. It should getString(), not getJsonString()
9

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.