Java 如何过滤JSON对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27420014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter JSON object
提问by Tej Kiran
I have a JSON object that is a list of Students that have Name, FName, City, Class, Contact. Now I want to filter only the objects (Students) which belong to the specific city. Can I filter the mail json object
我有一个 JSON 对象,它是一个包含姓名、FName、城市、班级、联系人的学生列表。现在我只想过滤属于特定城市的对象(学生)。我可以过滤邮件 json 对象吗
{
"Students": [
{
"id": 1,
"Name": "Student1",
"FName": "FName1",
"Class": "I",
"City": "Delhi"
},
{
"id": 2,
"Name": "Student2",
"FName": "FName2",
"Class": "II",
"City": "Mumbai"
},
{
"id": 3,
"Name": "Student3",
"FName": "FName3",
"Class": "II",
"City": "Delhi"
},
{
"id": 4,
"Name": "Student4",
"FName": "FName4",
"Class": "III",
"City": "Mumbai"
}
]
}
How can I get sub json list of students belongs to Delhi City?
如何获得属于德里市的学生的子 json 列表?
回答by Ankur Singhal
回答by Gábor Bakos
回答by Alexis C.
If you don't mind using a third-party library, you can use GSON. What you have to do is providing a custom deserializer to the Gson object. This deserializer will exclude all the Students objects that have the specific city value in their JSON representation.
如果您不介意使用第三方库,则可以使用GSON。您需要做的是为 Gson 对象提供自定义反序列化器。此反序列化器将排除在其 JSON 表示中具有特定城市值的所有学生对象。
public class Test {
public static void main(String[] args) throws Exception {
Type type = new TypeToken<List<Student>>() {}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(type, new Student.StudentListDeserializer("Mumbai")).create();
List<Student> list = gson.fromJson(new FileReader("myJson.json"), type);
System.out.println(list);
}
}
class Student {
private long id;
private String Name;
private String FName;
private String Class;
private String City;
@Override
public String toString() {
return "Student [id=" + id + ", Name=" + Name + ", FName=" + FName
+ ", Class=" + Class + ", City=" + City + "]";
}
static class StudentListDeserializer implements JsonDeserializer<List<Student>>{
private Set<String> forbiddenCities;
public StudentListDeserializer(String... forbiddenCities) {
this.forbiddenCities = new HashSet<>(Arrays.asList(forbiddenCities));
}
@Override
public List<Student> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
List<Student> list = new ArrayList<>();
for(JsonElement e : json.getAsJsonObject().get("Students").getAsJsonArray()) {
if(!forbiddenCities.contains(e.getAsJsonObject().get("City").getAsString())) {
list.add(context.deserialize(e, Student.class));
}
}
return list;
}
}
}
which outputs:
输出:
[Student [id=1, Name=Student1, FName=FName1, Class=I, City=Delhi], Student [id=3, Name=Student3, FName=FName3, Class=II, City=Delhi]]
回答by Aaryn Tonita
If you are using Java 8 the following works (note: I am using Hymanson, but as long as your JSON library returns a Map object for JSON objects, this example will still work):
如果您使用的是 Java 8,则以下工作(注意:我使用的是 Hymanson,但只要您的 JSON 库为 JSON 对象返回 Map 对象,此示例仍然有效):
// These 2 lines are Hymanson specific
ObjectMapper mapper = new ObjectMapper();
Map obj = mapper.readValue(s, Map.class);
List<Object> students = (List<Object>) obj.get("Students");
Object[] delhiStudents = students
.stream()
.filter(student -> ((Map)student).get("City").equals("Delhi"))
.toArray();
回答by mfe
You can use DSMlibrary. By using it you can filter JSON while you reading JSON data.
您可以使用DSM库。通过使用它,您可以在读取 JSON 数据时过滤 JSON。
Let's say you have POJO class for the student. Fields of student are not exactly matched with JSON data.
假设您为学生开设了 POJO 课程。student 的字段与 JSON 数据不完全匹配。
Student Class
学生班
public class Student {
private long id;
private String name;
private String firstName;
private String className;
private String city;
// getter/setter
}
You will define a yaml file that contains definitions of your mappings between json and Student class.
您将定义一个 yaml 文件,其中包含 json 和 Student 类之间的映射定义。
result:
type: array # result is list
path: /Students
filter: self.data.city=='Delhi' # filter by city field of class
fields:
id: long # id is long and path is the same as json id field.
name:
path: Name
firstName:
path: FName
className:
path: Class
city:
path: City
Use DSM to filter JSON and deserializeto Studentclass
用DSM过滤JSON和反序列化到学生类
DSM dsm=new DSMBuilder(new File("student.yaml")).create(Student.class);
List<Student> students= (List<Student>)dsm.toObject(new File("student.json");
Here is studentslist that converted to json.
这是转换为 json 的学生列表。
[ {
"id" : 1,
"name" : "Student1",
"className" : "I",
"city" : "Delhi",
"firstName" : "FName1"
}, {
"id" : 3,
"name" : "Student3",
"className" : "II",
"city" : "Delhi",
"firstName" : "FName3"
} ]