egervari
egervari

Reputation: 22522

Spring MVC Returns HTTP 400 when sending more JSON than expected

Currently I'm working on an ajax application that sends HTTP PUT requests via JSON to Spring 3.2 MVC controllers.

Everything is working fine except for the case where your JSON data does not match the expected @RequestBody class exactly:

@RequestMapping(value = "/{companyId}", method = RequestMethod.PUT)
public void update(@PathVariable long companyId, @Valid @RequestBody AdminCompanyForm adminCompanyForm) {
    adminCompanyService.updateCompany(companyId, adminCompanyForm);
}

For example, let's say we are sending a JSON object containing id and name fields, but the @RequestBody object only contains a single field called name.

In this case, Spring MVC will send an HTTP 400 response code (i.e. Bad Request) without any other form of error message. The solution is to change our Javascript code so that the JSON data only contains a name field. When doing that, everything works perfectly.

My question is this: How can I tell Spring not to send an HTTP 400 error when too much JSON is sent to an HTTP PUT action on one of my controllers? When an extra id field is sent via JSON, I want Spring to simply ignore it. I don't want it to be too strict. Having to manually delete JSON fields to match what the server expects exactly is honestly extremely time consuming, and I want to make my life easier.

Is there any way to achieve what I want?

Thanks!

Upvotes: 1

Views: 2565

Answers (1)

Yugang Zhou
Yugang Zhou

Reputation: 7283

Configuring the object mapper,

ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

You may write a simple test case with this object mapper. It will ignore unrecongized fields.

Now we need to configure spring mvc to use this custom object mapper. You may write a factory bean returnning ObjectMapper:

<mvc:annotation-driven>
<mvc:message-converters>
    <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
    <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="objectMapper" ref="jacksonObjectMapper" />
    </bean>        
</mvc:message-converters>
</mvc:annotation-driven>

 <bean id="jacksonObjectMapper" class="yourCustomObjectMapper" />

Upvotes: 5

Related Questions