Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 teach the Jackson mapper to ignore properties without binding fields.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading