askandanswer askandanswer - 4 years ago 148
JSON Question

Get a object from json based on a specific value

I have a json string. I need to get a specific object based on an id value. Suppose I entered 2, then I want

{"id":"2","name":"def"}
as the result. I want this to be done in java class.

[
{"id":"1",
"name":"abc"},
{"id":"2",
"name":"def"}
]

Answer Source

Put the Objects in the Array for better manipulation..!!!

JSONObject data = new JSONObject(YOUR_JSON);
JSONArray data_Values=data.getJSONArray(values);
int n=2;// Entered ID
for(int i=0;i<=data_Values.length();i++)
{ 
    if(n==data_Values.getInt("id"))
    {
        id=data_Values.getInt("id");
        name=data_Values.getString("name");
    }
}


JSON Data
    {
      "Values": [
        {
          "id": "1",
          "name": "ABC"
        },
        {
          "id": "2",
          "name": "EFG"
        },
        {
          "id": "3",
          "name": "HIJ"
        }
      ]
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download