使用jackson做反序列化的時(shí)候, 可能會(huì)報(bào)類(lèi)似的錯(cuò)誤:
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?)
這是因?yàn)閷?duì)象沒(méi)有默認(rèn)構(gòu)造函數(shù).
最簡(jiǎn)單的做法當(dāng)然是加入一個(gè)無(wú)參構(gòu)造函數(shù), 但是有的時(shí)候我們無(wú)法修改目標(biāo)對(duì)象, 這里有個(gè)解決方法, 擴(kuò)展類(lèi)并且使用@JsonProperty, 測(cè)試用例如下:(使用了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);
}
}
}