简体   繁体   中英

remove object from json array based on condition using java

In my application I get output in the form of Json array as below

{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.

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. Assuming you are receiving the JSON as a string named 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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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