【问题标题】:Post array of json objects to Spring MVC Controller将 json 对象数组发布到 Spring MVC 控制器
【发布时间】:2014-08-28 10:04:50
【问题描述】:

我在发送和接收 json 对象列表 (jQuery Ajax) 时遇到问题

Java 对象

public class UserSkill () {

 private long user;
 private long skill;
 private long level;

 //getter and setter methods

}

从控制器我得到对象列表,它看起来像这样

$.getJSON("getList", function(data) {
    console.log(data);
});

//console log ->  [Object { user=4, skill=61, leve=10}, Object { user=3, skill=61, level=20}]

我更改了一些值,我们有以下代码

ioarray = [];

//update methods

console.log(ioarray);

//console log ->  [Object { user=4, skill=61, level=9000 }, Object { user=3, skill=61, level=100 }]

Ajax POST

$.ajax({
    url : 'goUpdate',
    type : 'POST',
    contentType : 'application/json; charset=utf-8',
    dataType : 'json',
    data: ioarray,
    succcess : function(e) {
        alert('Yeah');
}

控制器

@RequestMapping(value = "goUpdate", method = RequestMethod.POST)
    public Object goUpdatePOST(@RequestBody List<UserSkill> list) {

        //list.get(0).getLevel(); 

        return list;
}

日志

type Status report

message Request method 'POST' not supported

description The specified HTTP method is not allowed for the requested resource.

这里出了点问题...有什么想法吗?

更新;

控制器

@RequestMapping(value = "goUpdate", method = RequestMethod.POST)
public @ResponseBody String goUpdatePOST(@RequestBody UserSkill[] list) {

    for(UserSkill i : list) {
        System.out.println(i.getSkill());
    }
    return "somepage";

} 

jQuery

var ioarray = [{ user:4, skill:61, level:10}, 
{ user:3,  skill:61, level:20}];

        $.ajax({
            url : 'goUpdate',
            type : 'POST',
            data: JSON.stringify(ioarray),
        });

控制台输出

JSON
0
    Object { user=4, skill=61, level=10}

1
    Object { user=3, skill=61, level=20}

Source
[{"user":4,"skill":61,"level":10},{"user":3,"skill":61,"level":20}]

在 pom.xml 中插入了 jackson-mapper-asl 和 jackson-core-asl。

当然这个例子会产生同样的错误......我做错了什么?我想我检查了所有可能性。

【问题讨论】:

  • 尝试删除dataType : 'json'
  • 否... POST 来源:undefined=&undefined=
  • 尝试删除@RequestBody 然后,发布的数据及其类型存在一些问题。
  • 我确实喜欢在数据中:{list: ioarray},仍然像上面一样出现,但现在发布:list%5B0%5D%5Buser%5D=4&list%5B0%5D%5Bskill%5D= 61&list%5B0%5D%5Blevel%5D=10&list%5B1%5D%5Buser%5D=3&list%5B1%5D%5Bskill%5D=61&list%5B1%5D%5Blevel%5D=20
  • 所以现在您的数据正在使用 UT-8 格式进行编码,请尝试删除 dataType : 'json'

标签: jquery ajax json spring


【解决方案1】:

这对你有用吗

    $.ajax({
        url : 'goUpdate',
        type : 'POST',
        data: JSON.stringify(ioarray),
        dataType: "json",
        contentType: "application/json"
    });

【讨论】:

  • 它也不起作用......我认为它可能不是JSON的问题,但还有什么?
  • @user2363971 你能用萤火虫检查数据中究竟发布了什么
  • 接受应用程序/json, text/javascript, /; q=0.01 Accept-Encoding gzip, deflate Accept-Language pl,en-US;q=0.7,en;q=0.3 Content-Length 97 Content-Type application/json; charset=UTF-8 Cookie JSESSIONID=BF78D2145022CEAC47AF35260444E8B2 Host localhost:8069 Referer localhost:8069/xxx/indexpage User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0 X-Requested-With XMLHttpRequest
  • @user2363971 我说的是发布请求,正在发布的 json
  • 我知道晚了,但问题是 (spring security)。您的解决方案是正确的。感谢您的帮助。
【解决方案2】:

尝试使用 value = "/goUpdate"

@RequestMapping(value = "/goUpdate", method = RequestMethod.POST)

【讨论】:

  • 有 goUpdate 路径前缀吗?还是像 localhost/goUpdate 一样运行??
【解决方案3】:

我遇到了同样的问题,我最后没有找到任何解决方案,我使用简单的HttpServletRequest找到了另一个解决方案。
您可以使用HttpServletRequest 读取请求数据并使用JSON API 将此json 字符串转换为List&lt;UserSkill&gt; 对象。您可以使用 GSON API 将您的 json 字符串转换为 list 。

为此,您需要在控制器类方法中进行以下更改,如下所示:

@RequestMapping(value = "goUpdate", method = RequestMethod.POST)
public @ResponseBody String goUpdatePOST(HttpServletRequest request) 
{
    String jsonStr = IOUtils.toString(request.getInputStream());
    Gson gson = new Gson();
    Type  fooType = new TypeToken<List<UserSkill>>() {}.getType();
    List<UserSkill> list = gson.fromJson(jsonStr,fooType);
    return gson.toJson(list);
}  

作为响应,发送 JSON 字符串,该字符串可以通过使用 Gson API 将 List&lt;UserSkill&gt; 转换为 JSON 字符串来创建。

希望这会对你有所帮助。

【讨论】:

    【解决方案4】:

    JS:

     $.ajax({
            type : "post",
            dataType : 'json', 
            url : 'addAdmin',  
            data : JSON.stringify(ioarray)
     })
    

    控制器(注意它只需要一个自定义字符串)。然后它使用 Jackson 手动解析字符串,因为在这种情况下 Spring 不会这样做。 (只有在使用 @ModelAttribute 表单绑定时,Spring 才会自动解析。)

    @PostMapping("/addAdmin")
    public boolean addAdmin(@RequestBody String json) throws Exception {
    
          String decodedJson = java.net.URLDecoder.decode(json, "UTF-8");
          ObjectMapper jacksonObjectMapper = new ObjectMapper(); // This is Jackson
          List<UserRolesGUIBean> userRolesGUIBeans =  jacksonObjectMapper.readValue(
                  decodedJson, new TypeReference<List<UserRolesGUIBean>>(){});
          // Now I have my list of beans populated.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 2017-02-22
      • 2011-08-19
      • 2013-01-11
      • 2012-11-26
      • 2014-05-28
      相关资源
      最近更新 更多