0

I have used following code to convert string to json and parse it.

String sb= {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"api_key": "c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e", "homeAddress": "kathmandu", "resource_uri": "/api/ca/entry/1/", "username": "sumit"}]}
    try {

                    JSONObject jsonObject = new JSONObject(sb);
                    JSONObject object = jsonObject.getJSONObject("objects");  
                    String api_key= object.getString("api_key");  
                    Toast.makeText(HelloWorldActivity.this, api_key, Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
                             e.printStackTrace();
                            }

Following some tutorials i tried to parse the json, but i am not able to parse it. for example : i want to return api_key as c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e

any thing that i have mistaken in above code

hangman
  • 865
  • 5
  • 20
  • 31
  • look at this answer: http://stackoverflow.com/questions/10947065/json-parsing-in-android-no-value-for-x-error/10947108#10947108 – ariefbayu Jun 18 '12 at 10:34

1 Answers1

2

Always use JSONLint or similar sites to well format your JSON.

Your JSON is like this

{
    "meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 1
    },
    "objects": [
        {
            "api_key": "c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e",
            "homeAddress": "kathmandu",
            "resource_uri": "/api/ca/entry/1/",
            "username": "sumit"
        }
    ]
}

here "objects" will return array not object.

Change you code to following.

    try {

            JSONObject jsonObject = new JSONObject(sb);
            JSONArray array = jsonObject.getJSONArray("objects");

            String key = array.getJSONObject(0).getString("api_key");
            String uname = array.getJSONObject(0).getString("username");
            Toast.makeText(HelloWorldActivity.this, username + " " + key,
                    Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Vipul
  • 27,808
  • 7
  • 60
  • 75