3

我有一个弹簧控制器方法,它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,如果这是所有有用的信息。

4

1 回答 1

0

在引入自定义之前,您的调度程序 servlet 配置和依赖项配置是什么样的MappingJackson2HttpMessageConverter

由于 Spring 使用Content-type您的请求标头来确定要使用哪个消息转换器,application/json当您的请求正文显然不是 JSON 时,您为什么要显式发送?

一个适当的“解决方法”是 send Content-type: text/plain,这将使 Spring 使用StringHttpMessageConverter我相信 Spring 在您开始配置之前所做的事情MappingJackson2HttpMessageConverter

于 2016-12-05T20:38:19.963 回答