我有一个像这样的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
}
有人可以帮我解决这个问题吗? :)
答案 0 :(得分:1)
您可以尝试以下方法:
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;
}
代码是不言自明的,因此省略了注释,希望对您有所帮助。
答案 1 :(得分:0)
您可以在ArraList
中创建HashMap
,以存储完整的JSON
数据。
这是示例代码。
public String MethodName(String json, String search) {
try {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
JSONArray jsonArray = new JSONArray(json);
ArrayList<HashMap<String, String>> data = new ArrayList<>();
for (int i = 0 ; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (search.equalsIgnoreCase(jsonObject.getString("name"))) {
array.put(jsonObject);
}
}
return array.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
答案 2 :(得分:0)
创建一个pojo类,即用户
class User{
String name;
String city;
String age;
// constructor with empty body
public User(){}
public User(String name,String city,String age){
this.name = name;
this.city = city;
this.age = age;
}
// create getter and setter here
public String getName(){
return this.name;
}
public String getCity(){
return this.city;
}
public String getAge(){
return this.age;
}
}
现在使用返回类型User Class创建所需的方法
public User getUserInfo(String json, String search) {
User user;
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0 ; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (search.equalsIgnoreCase(jsonObject.getString("name"))) {
String name = jsonObject.getString("name");
String city = jsonObject.getString("city");
String city = jsonObject.getString("age");
user = new User(name, city, age);
}
}
return user;
} catch (Exception e) {
e.printStackTrace();
}
现在调用方法并从User类对象获取数据
User user = obj.getUserInfo(json, search);
String name = user.getName();
String city = user.getCity();
String age = user.getAge();