📌  相关文章
📜  https:stackoverflow.com 问题 27420014 how-to-filter-json-object - 任何代码示例

📅  最后修改于: 2022-03-11 15:00:19.488000             🧑  作者: Mango

代码示例1
public class Test {
    public static void main(String[] args) throws Exception  {
        Type type = new TypeToken>() {}.getType();

        Gson gson = new GsonBuilder().registerTypeAdapter(type, new Student.StudentListDeserializer("Mumbai")).create();
        List 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>{

        private Set forbiddenCities;

        public StudentListDeserializer(String... forbiddenCities) {
            this.forbiddenCities = new HashSet<>(Arrays.asList(forbiddenCities));
        }

        @Override
        public List deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
            List 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;
         }               
     }        
}