1

I wondered if someone could answer a question for me as I dont quite understand why I needed to read a json object from the request input stream when I passed one to a spring controller manually.

Normally I use a json-rpc framework and it handles everything for me so I hadnt actually had to do this manually until now. Everything works ok but what I dont understand is why there was nothing in the request like when you post a form, and instead I had to use this code to map my object to Jackson:

BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
ChartParameters chartParameters = mapper.readValue(bis, ChartParameters.class);

I would just like to understand why I needed to read in the input stream and pass this to jackson instead of being able to get a value as a string which I first thought I would have to do.

Thanks in advance for any helpful answers.

4

2 回答 2

1

您可以将 JSON 作为字符串发布,并且可以配置:

    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    </bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
      <list>
        <ref bean="jacksonMessageConverter"/>
      </list>
 </property>
 </bean>
于 2013-07-11T07:23:09.520 回答
1

如果您使用的是最新的 Spring 版本,那么以下内容应该足以让事情顺利进行:

@ResponseBody
public Chart handleChartJsonRPC(@RequestBody ChartParameters chartParameters) throws Exception {
    return jsonService.getBarChart(chartParameters);
}

这(显然)假设您jsonService返回一个Chart对象,该对象应在将其发送回浏览器之前序列化为 JSON。

确保您有一个 MessageConverter,它将(反)序列化您的对象与 JSON 之间的序列化,如@user2054820 所述。

于 2013-07-11T07:38:00.067 回答