我有一个
String s =
{
"code1" : {
"price" : 100,
"type" : null
},
"code2" : {
"price" : 110,
"type" : null
}
}
然后我这样做:
Object p = Mapper.readValue(s, Person.class);
因此它执行了Person.class
中用@JsonCreator
注释的方法:
@JsonCreator
static Person create(Map<String, Object> s) {
s = Maps.filterValues(s, Predicates.instanceOf(Person.class));
...
}
我的问题是 s
始终为空。我检查了一下,这些值有一个价格
和一个类型
。但是当我执行 ps.get("code1").getClass()
时,它会给我 LinkedHashMap
。
我不明白发生了什么...你有任何线索吗?
这是我的类Person
(它是一个内部类):
public static class Person{
private int price;
private String type;
public Person(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
public String getType() {
return type;
}
}
谢谢!
最佳答案
问题是您将 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)
配置 objec 映射器时,它只会向您的映射添加一个空的 Person 实例,而不是抛出异常。
因此,您还应该定义一个方法,该方法将回答 Person 的实例是否为空,然后使用它过滤您的 map 。
如果您使用 java 8,您在过滤 map 时可以使用更少的代码:
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?"
}
}
您将获得相同的结果,就好像该字段从未存在过一样。
关于java - 为什么 Predicates.instanceOf 返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900025/