Jackson deserialize array with empty object

。_饼干妹妹 提交于 2019-12-24 01:01:38

问题


I have the following JSON:

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

and the corresponding POJO classes:

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

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

I would like jackson to deserialize to BeanA with an array of BeanBs, the first element would be just an instance of BeanB and the second with be an instance of BeanB with the name property set.

I've created the original string by serializing this:

BeanA beanA = new BeanA();
BeanB beanB = new BeanB();
beanB.setName("Will");
beanA.setBeans(new BeanB[] {new BeanB(), beanB});

Here's my full configuration for 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);

The error I get is this:

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:


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


来源:https://stackoverflow.com/questions/46571451/jackson-deserialize-array-with-empty-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!