如何解决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 举报,一经查实,本站将立刻删除。