9

I have the following endpoint :

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
public class TestController {

    @RequestMapping(value = "/persons", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<Integer> create(@RequestBody Person person) {
        // create person and return id
    }
}

Today if I received a request with an unknown field like this :

{
    "name" : "Pete",
    "bijsdf" : 51
}

I create the person and ignore the unknown field.

How can I check that there's an unknown field and then return a bad request ?

eLRuLL
  • 18,488
  • 9
  • 73
  • 99
Maxence Cramet
  • 552
  • 1
  • 5
  • 17
  • What JSON library are you using? I think this is the default in Jackson – Neil McGuigan Apr 08 '15 at 17:04
  • Hi Neil, yes it's jackson 2.5.0 that I used – Maxence Cramet Apr 08 '15 at 17:06
  • Yup, Jackson takes care of that. Is your `Person` class annotated with `@JsonIgnoreProperties(ignoreUnknown = true)`? – Rohit Jain Apr 08 '15 at 17:06
  • There is no annotation on my Person class – Maxence Cramet Apr 08 '15 at 17:11
  • Check this out: http://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html Default value for `ignoreUnknown` is `false`. That means Jackson (I'm looking at 2.5.0 doc) by default throws exception for missing fields. – Rohit Jain Apr 08 '15 at 17:14
  • IgnoreUnknown is set to false. I debug and I went to the method reportUnknownProperty of class DeserializationContext and it seems that the DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES is not enable. I'm looking where it is configured ... – Maxence Cramet Apr 08 '15 at 19:32

1 Answers1

6

Spring (4.1.2-RELEASE) use it's Jackson2ObjectMapperBuilder that by default disable FAIL_ON_UNKNOWN_PROPERTIES on overload jackson default behaviour. See this link to configure spring. Thx all for your helps

Community
  • 1
  • 1
Maxence Cramet
  • 552
  • 1
  • 5
  • 17