2

我有以下 JSON:

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

和相应的 POJO 类:

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

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

我希望杰克逊用 BeanB 数组反序列化为 BeanA,第一个元素将只是 BeanB 的一个实例,第二个元素是具有 name 属性集的 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 ('{}')
4

1 回答 1

2

使用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'}]}
于 2017-10-04T18:21:26.720 回答