我有一个
String s =
{
"code1" : {
"price" : 100,
"type" : null
},
"code2" : {
"price" : 110,
"type" : null
}
}那我就做:
Object p = Mapper.readValue(s, Person.class);因此,它在Person.class中执行带有Person.class注释的方法。
@JsonCreator
static Person create(Map<String, Object> s) {
s = Maps.filterValues(s, Predicates.instanceOf(Person.class));
...
}我的问题是s总是空的。我进行了检查,这些值有一个price和一个type。但是当我做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;
}
}谢谢!
发布于 2016-10-06 18:17:25
问题是,您正在将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实例为空,该方法将回答该问题,然后使用该方法筛选映射。
如果使用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?"
}
}您将得到相同的结果,就好像该字段从来不存在一样。
https://stackoverflow.com/questions/39900025
复制相似问题