Java Jackson ObjectMapper 继承问题

问题描述

public interface Vehicle {
    public default String getFourWheel() {
        throw new RuntimeException("Four Wheel not applicable");
    }

    public default String getTwoWheel() {
        throw new RuntimeException("Two Wheel not applicable");
    }
}

public class Bike implements Vehicle {
    private String twoWheel;    
    
    @Override
    public String getTwoWheel() {
        return twoWheel;
    }
    
    public void setTwoWheel(String twoWheel) {
        this.twoWheel = twoWheel;
    }
}

@Test
public void test_jacksonInheritance() throws JsonProcessingException {
    Bike bike = new Bike();
    bike.setTwoWheel("Two Wheeler");
    
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationInclusion(JsonInclude.Include.NON_ABSENT);
    objectMapper.writeValueAsstring(bike);
}

objectMapper 调用 getFourWheel(in interface) 并因此抛出 RuntTimeException: Four Wheel not 适用。

com.fasterxml.jackson.databind.JsonMappingException:四轮不适用(通过参考链:Bike["fourWheel"])

"com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:688)

如何阻止 objectMapper 不调用 getFourWheel,因为这在 Bike 类中不是必需的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)