杰克逊解串器不会因未知属性或缺失值而失败

时间:2016-03-30 15:41:38

标签: java serialization jackson java-8

当我尝试从字符串反序列化对象时,此字符串不包含某些字段或包含不在的字段我的对象,Jackson序列化程序完全没问题,只使用null / Optional.empty()字段创建我的Object,同时忽略未知属性。我尝试使用功能 FAIL_ON_UNKNOWN_PROPERTIES 设置阅读器,但没有成功。我有相当简单的Jackson配置,除了添加对Java 8和java.time的支持外,并没有多少。

编辑:

public final ObjectReader reader;
public final ObjectWriter writer;

private JsonMapperTestInstance() {
    ObjectMapper mapper = new JacksonConfiguration().objectMapper();
    reader = mapper.reader();
    writer = mapper.writer().withFeatures(SerializationFeature.INDENT_OUTPUT);
}
public <T> T deserialize(Class<T> actual, String serialized) throws IOException {
    return reader.forType(actual).readValue(serialized);
}

JacksonConfiguration:

@Primary
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    registerModules(mapper);
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    return mapper;
}
@Bean
public JavaTimeModule javaTimeModule() {
    return new JavaTimeModule();
}
@Bean
public Jdk8Module jdk8Module() {
    return new Jdk8Module().configureAbsentsAsNulls(true);
}
private void registerModules(ObjectMapper mapper) {
    mapper.registerModule(jdk8Module());
    mapper.registerModule(javaTimeModule());
}
@Primary
@Bean
public ObjectWriter writer(ObjectMapper mapper) {
    return mapper.writer();
}
@Primary
@Bean
public ObjectReader reader(ObjectMapper mapper) {
    return mapper.reader();
}

1 个答案:

答案 0 :(得分:0)

我已经确定注释@JasonUnwrapped会导致此行为。如果没有它,杰克逊就会对“very_wrong_field”的财产进行预测,而这个财产以前默默无视。