Spring MVC:POST请求带有列表的Json对象返回400错误请求

时间:2015-07-04 11:02:36

标签: java json spring rest spring-mvc

当我向JSON对象添加数组时,我的POST请求收到400 BAD REQUEST错误。

MemberDTO.java

public class MemberDTO{
private String memberId;
private String purchaseDate;
private List<ProductDTO> selectedProductModels;
...
}

ProductDTO.java

public enum ProductDTO {
  PRODUCT1("Product 1", "12.00", "50%', "500.00"),
  PRODUCT2("Product 2", "120.00", "80%', "100.00");

  private String productName;
  private String discount;
  private String retailPrice;
  private String price;
....
}

Controller.java

@RequestMapping(value = "member/purchase", method = RequestMethod.POST)
public String purchase(@RequestBody MemberDTO data){
 ...
 }

JSON

var purchaseData = {
    "memberId" : "12312",
    "purchaseDate" : "2015/02/14",
    "selectedProductModels" : [{
         "productName" : "sample1",
         "discount": "10%",
         "retailPrice": "100.00",
         "price": "400.98"
     },{
         "productName" : "sample2",
         "discount": "20%",
         "retailPrice": "1400.00",
         "price": "4300.98"
     }]
};

Ajax请求

$.ajax({
        type    : "POST",
        url     : contextPath + "/member/purchase.do",
        dataType: "json",
        contentType:"application/json",
        data    : JSON.stringify(purchaseData),
        success : function(data) {}
});

我尝试删除&#34; selectedProductModels&#34;来自json的数组列表,我得到了成功的回复。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

请尝试参考此处讨论的枚举反序列化选项

Jackson enum Serializing and DeSerializer

Serializing enums with Jackson

Converting JSON to Enum type with @RequestBody

您可以指定确切的值&#34;产品1&#34;,&#34; 12.00&#34;,&#34; 50%&#34;,&#34; 500.00&#34;在你的枚举常量中指定,因为只能解析那些值,否则你必须编写一个自定义的JSON反序列化器

注意:&#34;产品1&#34;,&#34; 12.00&#34;,&#34; 50%&#39;,&#34; 500.00&#34;你的文字中有一个单引号是类型错误吗?