杰克逊用空对象反序列化数组

时间:2017-10-04 18:09:10

标签: java json objectmapper jackson2

我有以下JSON:

{"beans":["{}",{"name":"Will"}]}

和相应的POJO类:

public class BeanA {
    private BeanB[] beans;
    ...getters/setters
}

public class BeanB {
    private String name;
    ...getters/setters
}

我希望jackson使用BeanBs数组反序列化为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 ('{}')

1 个答案:

答案 0 :(得分:1)

使用ObjectMapper#readValue

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'}]}