你必須設置對傑克遜使用的ObjectMapper參數:
objMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
這是Spring MVC中設置的一個辦法:
定義自定義對象的映射是這樣的:
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper(){
super.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
super.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}
註冊這個定製ObjectMapper:
<mvc:annotation-driven >
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
<property name="objectMapper">
<bean class="....CustomObjectMapper"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
此外,在您的要求,您就會需要有一個「應用程序/ JSON」的「接受」標頭
我有傑克遜Http消息,請不要認爲在json中添加一個參數不在對象中會導致requestBody問題? – insomiac 2012-07-29 22:16:50
是的,這是此參數的javadoc所說的內容: >應確定是否遇到未知屬性(不映射到屬性的屬性,並且沒有「任何setter」或可以處理它的處理程序)的功能失敗時(通過拋出JsonMappingException)。此設置僅在嘗試了所有其他未知屬性的處理方法後才生效,並且屬性保持未處理狀態。 – 2012-07-29 22:25:25
我應該在哪裏放置objectMapper配置? – insomiac 2012-07-29 23:00:39