反序列化具有数组数组的对象(Ajax调用+ C#)

时间:2014-09-14 12:29:04

标签: c# javascript arrays ajax json

我很难解决具有两个属性的对象的反序列化问题,一个是简单的字符串,另一个是数组数组(而数组中的每个元素都有一个名称和一个值)。

POST操作很有效,直到我到达服务器端,我能够在那里进行调试,但无法正确反序列化传递的数据。 我正在尝试将someData对象反序列化为服务器端的RequestObject

我想得到你的建议,因为我浪费了我的最后几个小时

在客户端:( JavaScript)

var dataArrays = [];
dataArrays[0] = [ {"name":"key","value":"xyz"} ];
dataArrays[1] = [ {"name":"firstname","value":"john"}, {"name":"lastname","value":"doe"} ];

var someData = {
someKey: "xyz",
dataArrays: dataArrays
};

$.ajax({
        type: 'POST',
        url: './mywebservice.asmx/Test',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(someData), ..);

在服务器端:(C#)

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string Test(string someKey, string dataArrays)
    {
        // someKey has the value: "xyz"
        // dataArrays is a string in the following format:
        // [[{"name":"key","value":"xyz"}],[{"name":"firstname","value":"john"}{"name":"lastname","value":"doe"}]]

        //unable to deserialize in here in any way
        // ?? RequestObject requestObj = JsonConvert.DeserializeObject<RequestObject> ??

    }

    [DataContract]
    public class StringData
    {
        [DataMember]
        public string name { get; set; }
        [DataMember]
        public string value { get; set; }
    }

    [DataContract]
    public class RequestObject
    {
        [DataMember]
        public string someKey { get; set; }
        [DataMember]
        public List<StringData[]> dataArrays{ get; set; }
    }

1 个答案:

答案 0 :(得分:0)

我最终通过将请求对象更改为

来解决它
 [DataContract]
    public class RequestObject
    {
        [DataMember]
        public string someKey { get; set; }
        [DataMember]
       public List<List<StringData>> dataArrays{ get; set; }
    }