问题
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