Configure FAIL_ON_UNKNOWN_PROPERTIES for each RequestMapping differently in the Controller

jsonignoreproperties(ignoreunknown = true spring boot)
jackson ignore field deserialization

I want to handle json to Object conversion differently on different @RequestMapping in my Controller.

I believe if we add Jackson dependency in our spring-boot project it handles json to Object conversion and #spring.jackson.deserialization.fail-on-unknown-properties=true property will make sure that conversion will fail if there is some unknown property present in the json (please correct me if I am wrong).

Can we tell jackson locally when to fail on unknown properties and when to ignore those property.

Following is code snippet to use a flag.

    @GetMapping(value = "sample")
    public @ResponseBody UserDTO test(@RequestParam String str, @RequestParam boolean failFast) {
        ObjectMapper map = new ObjectMapper();
        if( failFast) {
            map.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        } else {
            map.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
        UserDTO userDTO = null;
        try {
            userDTO = map.readValue(str, UserDTO.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userDTO;
    }

I don't need it to be handled at runtime like i am doing using @RequestParam. Is there some property using which i can use to mark mappings where to check for unknown properties and where to ignore them.

Edit: What I am looking for is to change an existing application to handle Unknown property per mapping. For example:

        @PostMapping(value = "fail/fast")
        public @ResponseBody UserDTO test(@FAIL_ON_UNKNOWN @RequestBody UserDTO userDTO, @RequestParam boolean failFast) {
            ..///processing...
            return userDTO;
        }

        @PostMapping(value = "fail/safe")
        public @ResponseBody UserDTO test( @RequestBody UserDTO userDTO, @RequestParam boolean failFast) {
                ..///processing...
                return userDTO;
        }

If some king of validation can be added per mapping then i don't need to change all existing mapping's to customise unknown property and code change will be minimum.


69. Spring MVC, I want to handle json to Object conversion differently on different @​RequestMapping in my Controller. I believe if we add Jackson dependency in our spring-boot  Update: my bad, as you can read in the section Advanced @RequestMapping options, multiple params are combined using and, not or, so it can't work as specified above.. So I'd say what you have to do is create an alias method with almost the same signature:


I was able to achieve the desired result by implementing my own HttpMessageConverter. Thanks to @MichalZiober for suggesting it.

I created a Custom HttpMessageConvertor and registered it with my custom MediaType:{"application", "json-failFast"}.

How this works is whenever Header: Content-Type:application/json-failFast is present then unknown properties in @RequestBody/@ResponseBody will not be accepted while converting from json to Object and UnrecognizedPropertyException will be thrown.

And whenever Header: Content-Type:application/json is present then unrecognised properties in @RequestBody/ResponseBody will be ignored.

Here is my custom HttpMessageConverter:

@Component
public class CustomJsonMessageConverter extends AbstractJackson2HttpMessageConverter {

    @Nullable
    private String jsonPrefix;

    public CustomJsonMessageConverter() {
        this(Jackson2ObjectMapperBuilder.json().build().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true));
    }
    public CustomJsonMessageConverter(ObjectMapper objectMapper) {
        super(objectMapper, new MediaType[]{ new MediaType("application", "json-failFast")});
    }

    public void setJsonPrefix(String jsonPrefix) {
        this.jsonPrefix = jsonPrefix;
    }

    public void setPrefixJson(boolean prefixJson) {
        this.jsonPrefix = prefixJson ? ")]}', " : null;
    }

    protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
            if (this.jsonPrefix != null) {
            generator.writeRaw(this.jsonPrefix);
        }
    }
}

Customizing HttpMessageConverters with Spring Boot and Spring , @RestController public class MyController { @RequestMapping("/thing") public MyThing thing() FAIL_ON_UNKNOWN_PROPERTIES is disabled You can configure the ObjectMapper and XmlMapper instances using the environment. They will be registered with every bean of type ObjectMapper , providing a global​  @RequestMapping is one of the most common annotation used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers. In this post, you’ll see how versatile the @RequestMapping annotation is when used to map Spring MVC controller methods.


@Autowired
private RequestMappingHandlerAdapter converter;

@Override
public void afterPropertiesSet() throws Exception {
    configureJacksonToFailOnUnknownProperties();
}

private void configureJacksonToFailOnUnknownProperties() {
    MappingJackson2HttpMessageConverter httpMessageConverter = converter.getMessageConverters().stream()
            .filter(mc -> mc.getClass().equals(MappingJackson2HttpMessageConverter.class))
            .map(mc -> (MappingJackson2HttpMessageConverter)mc)
            .findFirst()
            .get();

    httpMessageConverter.getObjectMapper().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}

Jackson, @RestController @RequestMapping("/rest/hotels") public class RestHotelController { . range of different resource representation formats - json, xml for instance. configuring the Jackson ObjectMapper, all that needs to be done with Spring FAIL_ON_UNKNOWN_PROPERTIES, false); jsonConverter. In my opinion this is a major security issue in spring. My application is exposing services which I call internally just because the team of the other service annotated their interfaces with @ RequestMapping on top level. This is not what I would expect. If I want a Controller to behave like a Controller it should be annotated as Controller.


Spring @RequestMapping, jackson ignore default value when it's true · Configure FAIL_ON_UNKNOWN_PROPERTIES for each RequestMapping differently in the Controller · more »  I've used this with Jackson 2.x and Spring 3.1.2+. servlet-context.xml: Note that the root element is <beans:beans>, so you may need to remove beans and add mvc to some of these elements depending on your setup.


Spring Boot 2.1.1.RELEASE Reference, Spring @RequestMapping - Basic Example, @RequestParam, How to configure HttpMessageConverters for a REST API with Spring, Even more flexible mappings are allowed – multiple params values can be set, and not all of them request mappings to be the same for different controller methods. Here you can see that Spring Boot has overridden the default logging level of logback by setting the root logger to INFO, which is the reason we did not see the debug messages in the example above


Ignoring Unrecognized JSON Fields With Spring & Jackson, Any Spring @RestController in a Spring Boot application should render JSON response @RestController public class MyController { @RequestMapping("/​thing") public MyThing FAIL_ON_UNKNOWN_PROPERTIES is disabled Note that, in either case, doing so disables all auto-configuration of the ObjectMapper . This is the controller method to handle typical HTTP Post request [for URL /user/create]. In a pure REST oriented approach, this controller method creates a user, and returns the HTTP 201[CREATED] along with a LocationHeader containing the locations of newly created user [/app-address/user/1 e.g].