0

I have a spring boot project that serves as a rest service. One of the endpoints, lets call it /search is a POST request method that uses a @RequestBody and maps it to a java object. The pojo is called SearchCriteria.

During testing, I found that if I misspell one of the requestBody parameters, that value does not get mapped to anything, but nothing bad happens(errors, exceptions, etc..). I want the 3 String values within the SearchCriteria object to be optional, that is not have to be provided in each json request, however is there a way to catch if an invalid parameter was passed in the body that did not get mapped?

An example of my question:

Let's say SearchCriteria.java has three String values (string1, string2, string3).

So in the first request, the body contains

   { 
     "string1":"abcd",
     "string2":"efgh",
     "string3":"ijkl"
   } 

This is a good request! However, in a subsequent request, I have a typo in my body(string1 is now strang1)

 {
    "strang1":"abcd",
     "string2":"efgh",
     "string3":"ijkl"
 } 

Is there a way to catch that this "strang1" is improperly spelled? I could always validate if string1, string2, and string3 are not null, but in my case they are optional so that is not valid. Also, even if they were mandatory, what if a 4th parameter was added on that is not included in the POJO? Say,

 {
    "strang1":"abcd",
     "string2":"efgh",
     "string1":"abcd",
     "string3":"ijkl"
 } 

Is there a way to catch bad Request Body objects that are not mapped to the RequestBody object?

DevelopingDeveloper
  • 883
  • 1
  • 18
  • 41
  • Perhaps using something [like this](https://stackoverflow.com/questions/32038543/how-to-validate-a-json-object-in-java), invoked by a Filter. – Andrew S May 17 '18 at 16:54

1 Answers1

4

Spring-boot uses jackson for serialization and deserialization, so you can set

spring.jackson.deserialization.fail_on_unknown_properties=true

in your properties file, which should give you a 400 when you send in an unknown property.

Will M.
  • 1,864
  • 17
  • 28