2

客户端代码:

$.ajax({
        type: "POST",
        url: "../web/zittles",
        data: jsonformatdata,
        contentType: "application/json",
        dataType: "json",
    success: function(data)
        {
        alert("data from server : "+data);
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            alert("jqXHR.status = "+jqXHR.status); //getting status code 400 here
        }        
});

输出json数据:

{
        "id": 1,
        "No": "1234",
        "Desc": "Testing"
}

Java类:

public class Fizzle implements Serializable
{
    private String id;
    private String No;
    private String Desc;
    // getters and setters 
}

弹簧 3 控制器:

@RequestMapping(value = '/zittles', method = RequestMethod.POST, headers ="Content-Type=application/json")
    public @ResponseBody void doSomeThing (@RequestBody Fizzle fizzle) {

        //do something here
}

app-servlet.xml 有

<mvc:annotation-driven/>

Tomcat的/lib文件夹有

jackson-core-lgpl-1.9.10.jar
jackson-mapper-lgpl-1.9.10.jar

收到状态码 400 错误 -

"The request sent by the client was syntactically incorrect"

当我如下所示更改控制器代码时,它将 json 数据作为字符串。

public @ResponseBody void doSomeThing (@RequestBody String fizzle) {}

理想情况下,杰克逊应该自动将 json 数据映射到 Fizzle 对象。

我在这里想念的是什么。要正确配置 Jackson 解析器,还需要做些什么吗?

请帮忙。

4

2 回答 2

2

Id 必须是 long 或 int,而不是 String

 private int id;

编辑

也许试试这个 JSON:

{
        "id": 1,
        "no": "1234",
        "desc": "Testing"
}

并在 Fizzle 类中将属性更改为小写

Edit2 测试这是 Jakson 问题还是 Spring 问题。将您的 JSON 保存到文件并尝试将其转换为对象:

ObjectMapper mapper = new ObjectMapper();
Fizzle fizzle = mapper.readValue(new File("c:\\fizzle.json"), Fizzle .class);
于 2012-09-26T13:47:26.530 回答
0

我正在回答我自己的问题,因为它对我有用。感谢“真空”给我方向。我正在使用 List,因为我正在接收一组 json 数据。

@JsonTypeName
@RequestMapping(value = '/zittles', method = RequestMethod.POST, headers ="Content-Type=application/json")     
public @ResponseBody void doSomeThing (@RequestBody String fizzles) 
{          
     //do something here
     ObjectMapper mapper = new ObjectMapper();
     ArrayList list = mapper.readValue(new StringReader(fizzles), ArrayList.class);
     List<Fizzle> fizzles1 = mapper.convertValue(list, new TypeReference<List<Fizzle>>() {});
}
于 2012-10-01T12:18:51.620 回答