2016-03-01 45 views
0

我想将对象数组作为JSON字符串传递给Spring控制器。我的JSON格式的数据看起来像关于将JSON传递给Spring控制器的400(错误请求)

[{ 
    "id": 123456, 
    "name": "First Item" 
}, 
{ 
    "id": 78910, 
    "name": "Second Item" 
}] 

所以我发送到控制器

@RequestMapping(value = "/some/url", method = RequestMethod.POST, consumes = "application/json") 
public void doSomething(@RequestBody List<CustInfo> myCustInfoList) { 
    System.out.println("Message Received " + myCustInfoList); 
} 

这个AJAX调用

$.ajax({ 
    type: 'POST', 
    url: '/some/url', 
    contentType: 'application/json', 
    data: '[{"id": 123456, "name": "First Item"}, {"id": 78910, "name": "Second Item"}]', 
    success: function() { 
      consloe.log("Success"); 
      } 
}); 

为此,我有两个豆OuterCoverCustInfo。其中OuterCover具有CustInfoCustInfo的列表具有idname

public class OuterCover { 

    List<CustInfo> myCustInfoList; 

    //getter & setter 

} 

但我得到400(坏请求)在这个。任何建议?

回答

0

您需要将OuterCover类放入其他类中,因为请求具有OuterCover元素。例如。

class RequestDto{ 

    @JsonElement("outerCover") 
    private OuterCover outerCover; 

    //getters and setters 
} 

或者,你可以修改请求负载并删除 '外罩' 元素如:

[{ 
    "id": 123456, 
    "name": "First Item" 
}, 
{ 
    "id": 78910, 
    "name": "Second Item" 
}] 
+0

如果我想发送的'数据:{[{ “ID”:123456,“名“:”First Item“},{”id“:78910,”name“:”Second Item“}]}' –

+0

这将起作用,我在答案中增加了另一个解决方案。 –

+0

我不能在控制器中使用'OutCover'吗?我想避免需要创建一个类('RequestDto')。 –