Answers for "https://stackoverflow.com/questions/27420014/how-to-filter-json-object"

0

https://stackoverflow.com/questions/27420014/how-to-filter-json-object

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;
         }               
     }        
}
Posted by: Guest on August-13-2021

Code answers related to "https://stackoverflow.com/questions/27420014/how-to-filter-json-object"

Browse Popular Code Answers by Language