JSON Parsing in Android [duplicate]

This is a very simple JSON String

{"key1":"value1","key2":"value2"}

In order to get values for it use JSONObject like this :

JSONObject json_obj=new JSONObject(your json string);
String value1=json_obj.getString("key1");
String value2=json_obj.getString("key2");

This is a slightly complex json string

[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]

In order to extract values from this use JSONArray

JSONArray jArray=new JSONArray(your json string);
for(int i=0;i<(jArray.length());i++)
{
    JSONObject json_obj=jArray.getJSONObject(i);
    String value1=json_obj.getString("key1");
    String value2=json_obj.getString("key2");
}

Hope this helps a bit...........


You can also check out Google's GSON library here. The GSON user guide here has some useful examples to help get you started. I've found GSON to be simple and powerful.


See: http://developer.android.com/reference/org/json/package-summary.html

Primarily, you'll be working with JSONArray and JSONObject.

Simple example:

    try {
        JSONObject json = new JSONObject(jsonString);
        int someInt = json.getInt("someInt");
        String someString = json.getString("someString");
    } catch (JSONException e) {
        Log.d(TAG, "Failed to load from JSON: " + e.getMessage());
    }