问题是您正在将 json 反序列化为String
并且Object
您将一直LinkedHashMap
存在,因为java.lang.Object
没有任何自定义字段。
换一种方式试试:
public class Demo {
public static void main(String[] args) throws IOException {
String s = "{" +
" \"code1\" : {" +
" \"price\" : 100," +
" \"type\" : null" +
" }," +
" \"code3\" : {" +
" \"somethingElsse\" : false," +
" \"otherType\" : 1" +
" }," +
" \"code2\" : {" +
" \"price\" : 110," +
" \"type\" : null" +
" }" +
"}";
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Map<String, Person> mapPerson = mapper.readValue(s, MapPerson.class);
Map<String, Person> filteredMap = Maps.filterValues(mapPerson, new Predicate<Person>() {
@Override
public boolean apply(Person person) {
return person.isNotEmpty();
}
});
System.out.println(filteredMap);
}
public static class MapPerson extends HashMap<String, Person> {}
public static class Person{
private int price;
private String type;
public Person() {
}
public boolean isNotEmpty() {
return !(0 == price && null ==type);
}
@Override
public String toString() {
return "Person{" +
"price=" + price +
", type='" + type + '\'' +
'}';
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
}
当您使用它配置对象映射器时,configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
它只会将 Person 的空实例添加到您的映射中,而不是引发异常。因此,您还应该定义一个方法,该方法将在 Person 的实例为空时做出响应,然后使用它过滤您的地图。
如果您使用 java 8,则在过滤地图时可以使用更少的代码:
Map<String, Person> filteredMap = Maps.filterValues(mapPerson, Person::isNotEmpty);
顺便说一句,即使您在 JSON 的键值中有一些额外的字段,它也可以工作:
{
"code1" : {
"price" : 100,
"type" : null,
"uselessExtraField": "Hi Stack"
},
"code2" : {
"price" : 110,
"type" : null,
"anotherAccidentalField": "What?"
}
}
您将获得与该字段从未存在过的结果相同的结果。