Search code examples
javaspringjacksonjackson2

Block unknown json properties on certain classes


I have a configuration which if enables blocks unknown variables from passing through.

    @Value("${json.failOnUnknown:false}")
    private boolean failOnUnknown;

    Jackson2ObjectMapperBuilder build = new Jackson2ObjectMapperBuilder();

    if(!failOnUnknown) {
        build.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }
    else {
        build.featuresToEnable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

I want this so if someone sends a bad property to my service I block them. However, my service connects to other services and if they send in an unknown variable it fails as well. I want unknown variables to be ignored when my other services talk to my current service.

I have tried using

@JsonIgnoreProperties(ignoreUnknown=true)

To overwrite the FAIL_ON_UNKNOWN_PROPERTIES but it doesn't work.

Any ideas on how to block unknown variables in some classes and not others?


Solution

  • One solution you might get into is to create two separate ObjectMappers, one that ignores unknown properties and the other one that throws exceptions. You can disable fail on unknow property directly on your Object Mapper scope as following: objectMapper.disable(FAIL_ON_UNKNOWN_PROPERTIES);.

    The idea is that you could still create a global scoped object mapper as shown in your example you use almost everywhere except for those services that needs to fail on unknown properties whatever the context is.