Android JSONObject : Search function

AlbertSamuel picture AlbertSamuel · Jun 5, 2014 · Viewed 7.4k times · Source

I am trying to search from JSON code that has been received beforehand..

I was wondering are there any efficient way to search specific object? Or should i use straight forward search like looping and if statement?

I have parsing the JSON successfully, and it stored in my String variable.. The JSON contains Array of Objects..

Now i want to search for specific ObjectName and get the Whole Objects.. The JSON will be like

   [
     {
         "name":"blank",
         "date":"2014-06-05T00:44:30Z",
         "boolean":null,
     },
     {
         "name":"hello",
         "date":"2013-05-04T00:43:20Z",
         "boolean":null,
     }
   ]

I want to search for name = "hello" and get the last Array returned

Can anyone show me how?

Thanks a lot!

Answer

Shai Aharoni picture Shai Aharoni · Jun 5, 2014

You can use something like this:

String name;
JSONObject searchObject;

JSONArray array = new JSONArray(yourJsonString);

for (int i = 0; i < array.length(); i++) {
    JSONObject currObject = array.getJSONObject(i);
    name = currObject.getString("name");

    if(name == "hello")
    {
       searchObject = currObject        
    }
}

return searchObject