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

1

1 Answer 1

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();
        }
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.