Spring MVC:post request和json对象with array:bad request [英] Spring MVC : post request and json object with array : bad request

查看:103
本文介绍了Spring MVC:post request和json对象with array:bad request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spring MVC从http POST请求中检索参数。

I'm trying to retrieve parameters from a http POST request with Spring MVC.

请求包含以下json对象(content-type:application / json) ,它本身包含一组customObjects:

The request contains the following json object (content-type : application/json), which itself contains an array of customObjects :

{  
   "globalId":"338",
   "lines":[  
      {  
         "id": "someId",
         "lib":"blabla",
        ...

      }
   ]
}

这是我正在尝试使用的代码:

Here's the code I'm trying to use :

  @RequestMapping(method = RequestMethod.POST, value = "/valider")
  @ResponseBody
  public void valider(final HttpServletRequest request, @RequestParam("globalId") final String globalId, @RequestParam("lines") final MyCustomObject[] lines) {

所有我收到的是错误请求错误(http 400)。

All I'm getting is a "bad request" error (http 400).

是否可以单独检索两个参数globalId和lines?或者因为它们在同一个json对象中,它必须被处理有一个参数?如果Post请求中有多个参数,你如何处理?

Is it possible to separately retrieve the two parameters "globalId" and "lines" ? Or since they are in the same json object, it has to be treated has a single parameter ? How do you proceed when you have more than one parameter in a Post request ?

推荐答案

我认为你在找类似的东西`@RequestBody。创建一个类来表示您的JSON数据。在您的情况下,此类将包含两个成员变量 - globalId作为字符串,行作为它所代表的对象的数组。然后在您的控制器方法中,您将在此类类型上使用@RequestBody批注,以便Spring能够将JSON转换为对象。请查看以下示例。

I think you're looking for something like `@RequestBody. Create a class to represent your JSON data. In your case, this class will contain two member variables - globalId as a string and lines as an array of the object it represents. Then in your controller method, you will use the @RequestBody annotation on this class type so that Spring will be able to convert the JSON into object. Check the examples below.

http://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/

JQuery,Spring MVC @RequestBody和JSON - 让它协同工作

http://www.techzoo.org/spring-framework/spring-mvc-requestbody-json-example.html

这篇关于Spring MVC:post request和json对象with array:bad request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆