This post is to show how to force newer version of Spring (4.1.1.RELEASE and later) to return error when a JSON with unrecognized fields is deserialized.
Setup
Maven<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
Development
User.java
package com.example.model;
public class User {
private String id;
private String name;
// constructor, setters, getters
}
JSON
{
“id”: “28b60d1e-c650-11e7-abc4-cec278b6b50a”,
“name”: “John Smith”,
“nickname”: “Johnny”
}
Controller.java
package com.example.controller;
@RestController
public class Controller {
private UserService userService;
@PutMapping(“/user”)
public void updateUserInfo(@RequestBody User user) {
userService.updateUser(user);
}
}
I expected to see UnrecognizedPropertyException or 400 Bad Request when the JSON was sent in, but it did not happen. Adding the annotation @JsonIgnoreProperties(ignoreUnknown=false) to the POJO had no effect, either. It turns out Spring Framework has changed its default configuration. So in the Spring configuration xml, I have to override its behavior
context-config.xml
<mvc:annotation-driven">
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Holy crap, thank you so much for this post! I was going nuts trying to figure out why the same thing wad happening to me. Now I know why! Thanks again!
ReplyDeleteGlad to be helpful : )
DeleteI used annotation based configuration and when a json is passed containing unknown fields are passed, it throws 400
ReplyDeletebut is there any way to find what is the error or what property is unknown.
Your could find the fields that cause error from the Tomcat or Eclipse log
Delete