NewDroidDev
NewDroidDev

Reputation: 1686

How to know if object value is existing in JSON on android?

Hei I'm new to web service using android. I want to know how could I check if an value exist in JSON? Here is a sample JSON

{
   "contacts": [
     {
            "id": "c200",
            "name": "Michael Jordan",
            "email": "[email protected]",
            "address": "xx-xx-xxxx,x - street, x - country",
            "gender" : "male",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
     }
   ]
}

I want to know if the name Michael Jordan is existing in JSON. Please help me with this I only know how to check if the object exist in JSON using has but how if I want to check the value?

Upvotes: 2

Views: 1982

Answers (4)

Peshal
Peshal

Reputation: 1518

you will need to read the content into JSONObject. Then you can add this code snippet

JSONArray jsonArray = yourJSONObject.getJSONArray("contacts"); //here yourJSONObject is the object which has the array in your question.
for(int i = 0; i<jsonArray.length(); i++) {
 JSONObject jObject = jsonArray.getJSONObject(i);
 String name = jObject.getString("name");
 if(name.equals("Michael Jordan")) {
 System.out.println("Name Exists");
 }
}

Upvotes: 3

Saikat
Saikat

Reputation: 2623

if(myJSONObject.has("name"))
{
//get the value
 String* name=myJSONObject.getString("name");
if(name.equals("Michael Jordan"))
{
 //do something
}

check the JSONObject doc : http://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Upvotes: 0

Pavel Dudka
Pavel Dudka

Reputation: 20934

Not sure to what extend you need this to be explained, but let's assume you have successfully parsed input stream into a JSONObject:

public boolean isJordanHere(JSONObject root) {
    try {
        JSONArray contacts = root.getJSONArray("contacts");
        for(int i=0; i<contacts.length(); i++)
        {
            String name = contacts.getJSONObject(i).getString("name");
            if("Michael Jordan".equals(name))
            {
                return true;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    return false;
}

Upvotes: 2

Ryan S
Ryan S

Reputation: 4567

Couldn't you just search for the string since the json is just a string? Look at the contains function otherwise look into gson, this will allow you to serialize the json to an object

Upvotes: 0

Related Questions