Michael Nana
Michael Nana

Reputation: 1977

How to access values returned from JSON Object

So I'm working with returned values from a JSON object and I'm trying to return the values of one of its keys. So the JSON object I get is this.

{"options":[{"picture":"http:\/\/example.com\/1.png", contact_id="1", name="Tom"}, {"picture":"http:\/\/example.com\/2.png", contact_id="2", name="Jess"}]}

Now I'm handling it in an android app and when I have a final static String called say TAG which is set to options

private static final String TAG = "options";

and I use to log the json values like this

Log.d("Friends name", jsn.getString(TAG));

I get the first result

{"options":[{"picture":"http:\/\/example.com\/1.png", contact_id="1", name="Tom"},      {"picture":"http:\/\/example.com\/2.png", contact_id="2", name="Jess"}]}

However I'm trying to access the names only and I don't really know how to.

I tried setting TAG to options[0].name to get just the first name but it gave me an error

JSONException : No Value for options[0].name

I'm a bit lost here.

Upvotes: 1

Views: 187

Answers (3)

Vipul
Vipul

Reputation: 28093

If you are talking about JSON then the string you have posted is not a valid JSON.

It should be as follows.

{
    "options": [
        {
            "picture": "http://example.com/1.png",
            "contact_id": "1",
            "name": "Tom"
        },
        {
            "picture": "http://example.com/2.png",
            "contact_id": "2",
            "name": "Jess"
        }
    ]
}

Then write below snippet to fetch name.

JSONObject android = new JSONObject(json_string);

JSONArray array = android.getJSONArray("options");

for (int i = 0; i < array.length(); i++) {
    Log.i("name", array.getJSONObject(i).getString("name"));
}

Upvotes: 3

Deepanker Chaudhary
Deepanker Chaudhary

Reputation: 1704

JSONObject object=new JSONObject(Your String...);
JsonArray jArray=object.getJsonArray("options");
for(int i=0;i<jArray.length;i++)
{
  JSONObject jObject=jArray.getJSONObject(0);
 String picture=jObject.getString("picture"); 
 int id=JObject.getInt("contact_id");
  String name=JObject.getString("name");

 }

Upvotes: 0

Naresh
Naresh

Reputation: 3179

You need to create JSONArray and get the value as

JSONArray jsonArr = jsn.getJSONArray(TAG);
String name=jsonArr.get(0).getString("name");

Upvotes: 0

Related Questions