杰克逊用空对象反序列化数组
Jackson deserialize array with empty object
我有以下 JSON:
{"beans":["{}",{"name":"Will"}]}
和对应的POJO 类:
public class BeanA {
private BeanB[] beans;
...getters/setters
}
public class BeanB {
private String name;
...getters/setters
}
我希望 jackson 使用 BeanB 数组反序列化为 BeanA,第一个元素只是 BeanB 的一个实例,第二个元素是 BeanB 的一个实例,名称设置为 属性。
我通过序列化创建了原始字符串:
BeanA beanA = new BeanA();
BeanB beanB = new BeanB();
beanB.setName("Will");
beanA.setBeans(new BeanB[] {new BeanB(), beanB});
这是我对 objectMapper 的完整配置:
this.objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
我得到的错误是这样的:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `BeanB` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{}')
BeanA beanA = new BeanA();
BeanB beanB = new BeanB();
beanB.setName("Will");
beanA.setBeans(new BeanB[] {new BeanB(), beanB});
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
String json = om.writeValueAsString(beanA);
System.out.println(json);
// output: {"beans":[{},{"name":"Will"}]}
BeanA deserializedBeanA = om.readValue(json, BeanA.class);
System.out.println(deserializedBeanA);
// output: BeanA{beans=[BeanB{name='null'}, BeanB{name='Will'}]}
我有以下 JSON:
{"beans":["{}",{"name":"Will"}]}
和对应的POJO 类:
public class BeanA {
private BeanB[] beans;
...getters/setters
}
public class BeanB {
private String name;
...getters/setters
}
我希望 jackson 使用 BeanB 数组反序列化为 BeanA,第一个元素只是 BeanB 的一个实例,第二个元素是 BeanB 的一个实例,名称设置为 属性。
我通过序列化创建了原始字符串:
BeanA beanA = new BeanA();
BeanB beanB = new BeanB();
beanB.setName("Will");
beanA.setBeans(new BeanB[] {new BeanB(), beanB});
这是我对 objectMapper 的完整配置:
this.objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
我得到的错误是这样的:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `BeanB` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{}')
BeanA beanA = new BeanA();
BeanB beanB = new BeanB();
beanB.setName("Will");
beanA.setBeans(new BeanB[] {new BeanB(), beanB});
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
String json = om.writeValueAsString(beanA);
System.out.println(json);
// output: {"beans":[{},{"name":"Will"}]}
BeanA deserializedBeanA = om.readValue(json, BeanA.class);
System.out.println(deserializedBeanA);
// output: BeanA{beans=[BeanB{name='null'}, BeanB{name='Will'}]}