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

本文关键字:反序列化 Ajax 调用 +C# 数组 对象 | 更新日期: 2023-09-27 18:21:45

Im在反序列化具有两个属性的对象时遇到了很多困难,一个是简单字符串,另一个是数组数组(而数组中的每个元素都有一个名称和一个值)。

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; }
    }

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

我已经通过将RequestObject更改为来即时解决它

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