简体   繁体   中英

Jackson deserializer not failing on unknown properties or missing values

When I'm trying to deserialize Object from a String and this String does not contain certain fields or has fields that are not in my Object , Jackson serializer is completely okay with that and just creates my Object with null/Optional.empty() fields, also ignoring unkown properties. I tried to set reader with feature FAIL_ON_UNKNOWN_PROPERTIES but to no success. I have fairly simple Jackson configuration, not much besides adding support for Java 8 and java.time.

Edit:

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();
}

I have determined that annotation @JasonUnwrapped is causing this behaviour. Without it Jackson throws expection on property "very_wrong_field", which previously was silently ignoring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM