3

出于某种原因,我无法让 ServiceStack 序列化发布的 (serializeArray) 表单数据。发布的json是:

{"somestuff":"someData","formInput":[{"name":"1","value":"2"},...]}

我用来发布表单的 jQuery:

var formData = $("form").serializeArray();
            var data = {
                someOtherFields: some data,
                formInput: formData
            };
            $.ajax({
                type: "post",
                url: "/api/location",
                data: data,
                dataType: "json",
                success: function(response) {
                    if (response.status == "success") {
                        scope.showForm = false;
                        scope.status = "successfully added message";
                    } else {
                        scope.status = response.message;
                    }
                }
            });

这是发布到带有 DTO 的 ServiceStack 服务:

public class ServiceRequest
{
     other atributes;
     public List<ArraySerializeResult> FormInput { get; set; }
}

public class ArraySerializeResult
{
     public string Name { get; set; }
     public string Value { get; set; }
}

其他属性被序列化很好,但 formInput 被序列化为具有正确数量元素的列表,但所有名称和值对都为空。

4

2 回答 2

2

SerivceStack 期望您发送以JSV格式而不是JSON格式的复杂类型

您可以使用 ServiceStack 项目中的 JSV.js 之类的东西以 JSV 而不是 JSON 格式请求,或者实现您自己的Request Binder来反序列化 JSON。

public override void Configure(Container container)
{
    RequestBinders.Add(typeof (ServiceRequest), (IHttpRequest httpReq) => {
        var myRequest = new ServiceRequest();
        // Deserialize the request here using ServiceStack.Text or whatever you like...
        return myRequest;
     });
}
于 2013-10-10T17:07:14.547 回答
1

您应该在您的 ajax 请求中添加“contentType”选项。使用 content-type "application/json",servicestack 可以反序列化 json 数组

contentType: "application/json; charset=utf-8"

所以它看起来像这样

        $.ajax({
            type: "post",
            url: "/api/location",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                if (response.status == "success") {
                    scope.showForm = false;
                    scope.status = "successfully added message";
                } else {
                    scope.status = response.message;
                }
            }
        });
于 2015-03-14T17:26:35.223 回答