1

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.

3
  • 1
    First of all check your JSON output on jsonlint.com I checked the JSON you provided and it has an error.. Commented Jul 15, 2013 at 6:13
  • 1
    i think it should be ":" instead of "=". Commented Jul 15, 2013 at 6:13
  • Access the first name with jsn.options[0].name; In the case of yours - TAG = jsn.options[0].name;. Commented Jul 15, 2013 at 6:14

3 Answers 3

3

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"));
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to create JSONArray and get the value as

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

Comments

0
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");

 }

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.