我有一个像这样的 JSON 数组:
[
{
"name": "John",
"city": "chicago",
"age": "22"
},
{
"name": "John",
"city": "florida",
"age": "35"
},
{
"name": "Selena",
"city": "vegas",
"age": "18"
},
{
"name": "Selena",
"city": "Florida",
"age": "19"
}
]
我想在 Java 中实现一个函数,它可以获取 JSON 数组、值并返回一个 JSON 字符串,其中包含具有传递值的所有元素,示例:
public String returnSearch(JSONArray array, String searchValue){
// let us say if the searchValue equals John, this method
// has to return a JSON String containing all objects with
// the name John
}
谁能帮我解决这个问题吗? :)
请您参考如下方法:
你可以试试这个:
public String returnSearch(JSONArray array, String searchValue){
JSONArray filtedArray = new JSONArray();
for (int i = 0; i < array.length(); i++) {
JSONObject obj= null;
try {
obj = array.getJSONObject(i);
if(obj.getString("name").equals(searchValue))
{
filtedArray.put(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
String result = filtedArray.toString();
return result;
}
代码是不言自明的,因此省略注释,希望对您有所帮助。