【问题标题】:Is there a way to deserialize json into complex objects with spring mvc 3.1?有没有办法使用 spring mvc 3.1 将 json 反序列化为复杂对象?
【发布时间】:2012-08-28 18:35:23
【问题描述】:

我正在尝试找出一种通过 json 与 spring mvc 3.1 传递复杂对象的方法。我也在用knockoutjs,所以取ko.toJSON相当于JSON.stringify。

部署T

这里是 ajax 调用:

$.ajax({
            url: "/doAction",
            type: "post",
            data: ko.toJSON({"complexObjectA": ko.toJSON(self.complexObjectA()), "complexObjectB": ko.toJSON(self.complexObjectB()), "id": "", "text": ""}),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            // callback handler that will be called on success
            success: function (response, textStatus, jqXHR) {
                //dosomething
            },
            // callback handler that will be called on error
            error: function (jqXHR, textStatus, errorThrown) {
                // log the error to the console

            },
            // callback handler that will be called on completion
            // which means, either on success or error
            complete: function () {
                //dosomething
            }
        });

spring 控制器代码如下:

    @RequestMapping(value = "/doAction", method = RequestMethod.POST)
    @ResponseBody
    public String doAction(@RequestBody MyForm form, HttpServletRequest request, HttpServletResponse response) {

而 MyForm 是这样定义的:

public class MyForm {
private ComplexObjectA complexObjectA;
private ComplexObjectB complexObjectA;
private String id;
private String text;

使用适当的公共 getter/setter。

当我尝试拨打此电话时,我收到错误 400 客户端发送的请求语法错误()。

复杂的对象都是通过更早的 json get 获得的,它们可以很好地从对象序列化到 json 和 js 对象。

我需要用 Jackson 创建一个特殊的反序列化器才能做到这一点吗?

【问题讨论】:

    标签: json spring-mvc jackson


    【解决方案1】:

    正如您之前所说的您的复杂对象序列化成功,我可以猜测您的 Spring 配置文件没有问题,并且 Jackson 配置正确。我认为您不需要为 MyForm 类创建单独的序列化器/反序列化器。

    例如,如果您在用户单击具有非空 href 的链接时进行 jQuery AJAX 调用,则可能会出现 400 错误“错误请求”,因此浏览器会尝试执行默认操作。在这种情况下,您可以看到请求标头仍然具有“text/html”类型,尽管您正在尝试发送“application/json”。

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多