根据特定值从json获取对象

时间:2023-01-15 15:55:10

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.

我有一个json字符串。我需要根据id值获取特定对象。假设我输入2,那么我想要{“id”:“2”,“name”:“def”}作为结果。我希望这可以在java类中完成。

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

1 个解决方案

#1


0  

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"
        }
      ]
    }

#1


0  

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"
        }
      ]
    }