jackson "no suitable constructor found" Exception

使用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);
        }
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容