【问题标题】:Submitting nested object to REST controller将嵌套对象提交给 REST 控制器
【发布时间】:2014-12-24 03:13:29
【问题描述】:

我有一个 HTML 表单,其中有一个“嵌套”对象。 如果我仅发送带有纯属性的实体,内部没有其他实体,则可以,但是要使用 ajax 将表单发送到 REST 控制器,则会引发异常而不是事件到达控制器,因为此“嵌套”对象未重新识别为属性发送的主要实体,即Product

我可以在 ajax 操作中以两种不同的jquery 方式获取数据:

$.param($('form').serializeArray())
"id=&type.id=1&name=One"

JSON.stringify($('form').serializeArray())
"[{"name":"id","value":""},{"name":"type.id","value":"1"},{"name":"name","value":"One"}]"

在最后一种情况下,我当然可以创建一个 $.each jquery 函数来完全转换对象。 但是有什么方法可以使用jquery 或者配置良好的杰克逊映射器对象轻松转换它?

这里有表单、ajax 调用、java 实体和控制器。

表格:

<form>
   <input type="hidden" name="id"/>
   <select id="type.id">
     <option value='1'>One</option>
     <!-- ... -->
   </select>
   <input type="text" id="name"/>
</form>

实体:

@Entity
@Table
public class Product {
    @Id
    @GeneratedValue
    private Integer id;
    @ManyToOne
    private Type type;
    @Column(nullable = false, length = 250)
    private String name;

    /* getters and setters */
}

@Table
@Entity
public class Type {
    @Id
    @GeneratedValue
    @Column(length = 5)
    private Integer id;
    @Column(length = 50, nullable = false)
    private String name;

    /* getters and setters */
}

ajax 在某个按钮中提交:

$.ajax({
        type : "POST",
        url : "create",
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        data : /* 
                here stands the doubt. How serialize my form?
                */,
        success : function(data) {
            if (data === true) {
                alert('Success!');
            } else {
                console.log('Some error');
            }
        }
    });

控制器:

@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public Boolean create(@RequestBody Domain model) throws Exception {
    try {
        getService().create(model);
        return true;
    } catch (Exception e) {
        return false;
    }
}

【问题讨论】:

    标签: java rest model-view-controller jackson


    【解决方案1】:

    抱歉,我只是误解了你的问题。 这是另一种提供表单选择器并返回 json 对象的解决方案。

    function serializeForm(formSelector){
      var params = $.param($(formSelector).serializeArray());
      var jsonStr = '{"'+params.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"')+'"}';
      var jsonObj = JSON.parse(jsonStr);
      return jsonObj;
    }
    
    var formJsonData = serializeForm('form');
    

    【讨论】:

    • 但如果主对象有另一个对象作为主对象的字段,如我的问题示例'type.id'。对象映射器找不到“type.id”作为产品字段并引发异常。这是主要问题。
    【解决方案2】:

    这是另一个对象序列化器。

    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
    

    【讨论】:

    • 我刚试过,@Ghokun,但正如我在另一个答案的评论中所说:如果主对象有另一个对象作为主对象的字段,如我的问题示例“type.id”。对象映射器找不到“type.id”作为产品字段并引发异常。这是主要问题。
    【解决方案3】:

    你可以试试这个:

    控制器:

    @RequestMapping(value = "/create", method = RequestMethod.POST , headers = "Accept=application/json")
    @ResponseBody
    public Map<String, String> create(@RequestBody Domain model) throws Exception {
        HashMap<String, String> result = new HashMap<String, String>();
        try {
            getService().create(model);
            result.put("status",true);
        } catch (Exception e) {
            result.put("status",false);
        }
        return result;
    }
    

    ajax 在某个按钮中提交:

    $.ajax({
            type : "POST",
            url : "create",
            contentType : "application/json; charset=utf-8",
            dataType : "json",
            data : /* 
                    here stands the doubt. How serialize my form?
                    */,
            success : function(data) {
                if (data.status === true) {
                    alert('Success!');
                } else {
                    console.log('Some error');
                }
            }
        });
    

    【讨论】:

    • 感谢您尝试帮助我,史蒂文。但主要问题仍然是:如何序列化表单?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多