简体   繁体   English

使用Java根据条件从json数组中删除对象

[英]remove object from json array based on condition using java

In my application I get output in the form of Json array as below 在我的应用程序中,我得到如下Json数组形式的输出

{Students: [{Name: Harry,Subject: maths,}, 
               {Name:Ryan,Subject: Biology,}, 
               {Name:James ,Subject: maths,}]}

From this array I want to remove the whole object based on the applied condition. 从这个数组中,我想根据应用的条件删除整个对象。

Lets say if Subject is "Biology" remove the whole object and return: 假设主体为“生物学”,则删除整个对象并返回:

{Students: [{Name: Harry,Subject: maths,}, 
            {Name:James ,Subject: maths,}]}

How can I achieve this using java programming. 如何使用Java编程实现这一目标。

If You have the class (I assume Student here) you can unmarshall the object list using a serialization/deserialization library like Jackson to a collection like List and then do simple list manipulation. 如果您有课程(我在这里假设是学生),则可以使用序列化/反序列化库(如Jackson)将对象列表解组到诸如List的集合中,然后执行简单的列表操作。 Assuming you are receiving the JSON as a string named students 假设您收到的JSON是一个名为students的字符串

List<Student> list = mapper.readValue(students,
TypeFactory.defaultInstance().constructCollectionType(List.class, Student.class));

This should work. 这应该工作。

Edit: Since you asked for a version that reads JSON from a file, there you go: 编辑:由于您要求一个从文件中读取JSON的版本,因此您可以进行以下操作:

public JSONArray getFilteredStudents(String jsonFilePath) throws Exception {
        FileReader fileReader = new FileReader(jsonFilePath);
        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject) parser.parse(fileReader);

        JSONArray students = (JSONArray) json.get("Students");
        Iterator itr = students.iterator();
        while (itr.hasNext()) {
            JSONObject obj = (JSONObject) itr.next();
            if (obj.get("Subject").equals("Biology")) {
                itr.remove();
            }
        }

        return students;
}

Download json-simple library from here . 此处下载json-simple库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM