[英]Posting JSON object using Ajax
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. 我想知道是否有人可以为我回答一个问题,因为我不太了解为什么当我手动将一个传递给spring控制器时需要从请求输入流中读取json对象。
Normally I use a json-rpc framework and it handles everything for me so I hadnt actually had to do this manually until now. 通常,我使用json-rpc框架,它可以为我处理所有内容,因此到目前为止,我实际上还没有手动执行此操作。 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:
一切正常,但我不明白的是为什么请求中没有什么内容(例如发布表单时),而我不得不使用此代码将对象映射到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. 我只想了解为什么我需要读取输入流并将其传递给jackson,而不是能够以字符串形式获取值,这是我最初认为必须要做的。
Thanks in advance for any helpful answers. 在此先感谢您提供任何有用的答案。
You can post your JSON just as a string and you can configure : 您可以将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>
If you're on a recent Spring version, the following should be enough to get things rolling: 如果您使用的是最新的Spring版本,则以下内容应足以使事情进展:
@ResponseBody
public Chart handleChartJsonRPC(@RequestBody ChartParameters chartParameters) throws Exception {
return jsonService.getBarChart(chartParameters);
}
This (obviously) assumes your jsonService
returns a Chart
object, which should be serialised to JSON before sending it back to the browser. 这(显然)假设您的
jsonService
返回一个Chart
对象,在将其发送回浏览器之前,应将其序列化为JSON。
Make sure you have a MessageConverter that will (de-)serialise your objects to and from JSON, as described by @user2054820. 确保您有一个MessageConverter,该对象将按照@ user2054820的说明将对象与JSON进行反序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.