使用jackson做反序列化的时候, 可能会报类似的错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of test.jackson.case6.case5.ParseTest$SolidBean: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
这是因为对象没有默认构造函数.
最简单的做法当然是加入一个无参构造函数, 但是有的时候我们无法修改目标对象, 这里有个解决方法, 扩展类并且使用@JsonProperty, 测试用例如下:(使用了lombok)
public class ParseTest {
@Test
public void parseTest() throws IOException {
SolidBean solidBean = new SolidBean("content");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(solidBean);
System.out.println(json);
SolidBean deserialized = objectMapper.readValue(json, ExtendBean.class);
System.out.println(deserialized);
}
@Data
@AllArgsConstructor
public static class SolidBean {
String content;
}
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public static class ExtendBean extends SolidBean {
public ExtendBean(@JsonProperty("content") String content) {
super(content);
}
}
}