Search code examples
javajacksonspring-integration

Jackson ObjectMapper VS Spring integration JsonToObjectTransformer()


I got stuck on this and i’d like to clarify it better

The default behaviour of Jackson ObjectMapper is to throw exception in front of json properties which can’t be bind in any Java field.

// json to bind in java entity
{ "name":"mike", "surname":"parker", "age":19 }

// java entity
class Hero {

   String name;
   String surname;

}

// default mapper from Jackson
private final ObjectMapper objectMapper = new ObjectMapper();

// this will fail for Unrecognized field "age"
Hero spiderMan = objectMapper.readValue(json, Hero.class);
 

To avoid Unrecognized field Exception i should configure the Jackson mapper to ignore properties with

.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

On the other side from api doc i read that Spring Integration JsonToObjectTransformer() by default uses JsonObjectMapperProvider factory to get an instance of Jackson JSON-processor. The strange fact is that even if both are supposing to behave in the same way, it seems that they actually don’t. The JsonToObjectTransformer() allows unrecognized json property "age" and does not throw any exception. No other mapper are declared on it so i expected the use of the default Jackson mapper.

// same json coming from inputChannel but no exception is thrown and binding will success
@Bean
@Transformer(inputChannel = "myInputChannel", outputChannel = "myOuputChannel")
    JsonToObjectTransformer jsonToObjectTransformerHero() {

    return new JsonToObjectTransformer(Hero.class);
}

Am i misunderstanding something or are they actually acting in different way ?


Solution

  • Check out the way the actual internal ObjectMapper is initialized. Looks like it's preconfigured to ignore unknown properties:

    public Jackson2JsonObjectMapper() {
        this.objectMapper = JsonMapper.builder()
                .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false)
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .build();
        registerWellKnownModulesIfAvailable();
    }