我有一个弹簧控制器方法,它String
完全RequestBody
像这样:
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody DTO method(@PathVariable("userId") long userId, @RequestBody String page) {
// Controller contents here
}
以前,我已经能够将“裸”字符串发布到此方法,即以字符串作为主体(而不是 json 对象)的请求。例如(来自 chrome 开发工具):
在我尝试在我的 xml 配置文件中使用以下内容将Jackson Hibernate 4 模块添加到Jackson2ObjectMapperFactoryBean(以处理 hibernate 惰性集合)后,这停止了工作:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="modulesToInstall"
value="com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module"/>
<property name="featuresToEnable">
<array>
<util:constant static-field="com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES"/>
</array>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
像这样自定义 ObjectMapper 后,我在发布上述请求时收到以下错误:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'Testing': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@5e6a19fe; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Testing': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@5e6a19fe; line: 1, column: 13]
解决方法(使用角度 js)是JSON.stringify()
在发布到 API 之前调用,因此角度代码变为
$http.post(Url + userId, JSON.stringify(string)).then(function (result) {
return result.data;
});
并且请求变为
在此之后,API 像以前一样工作,自己接受字符串。
虽然我知道没有封闭的字符串"
不是有效的 JSON 字符串,但我不明白为什么在这种情况下更改 ObjectMapper bean 会产生如此大的差异?我正在使用 spring 版本 4.3.4 和 jackson 版本 2.8.5,如果这是所有有用的信息。