【问题标题】:JavaScriptDeseializer : Can not serialize arrayJavaScriptDeseializer:无法序列化数组
【发布时间】:2012-05-25 18:12:40
【问题描述】:

我的应用程序是 asp.net。我必须将一些值发送回服务器。为此,我创建了一个对象序列化它并将其发送到服务器。在服务器上,我尝试对其进行反序列化 以下是我的代码

   [Serializable]
    public class PassData
    {
        public PassData()
        {  
        }

        public List<testWh> SelectedId { get; set; }

        public string SelectedControlClientId { get; set; }

        public string GroupTypeId { get; set; }

        public string SectionTypeId { get; set; }

  }


    [Serializable]
    public class testWh
    {
        public testWh()

        {
        }
        public string Id { get; set; }
    }


JavaScriptSerializer serializer = new JavaScriptSerializer();
//this can not serialize the SelectedId and the count remains 0
PassData data = serializer.Deserialize<PassData>(jsonString);
//this serialize in an anonymous object with key value pair
var data2 = serializer.DeserializeObject(textHiddenArguments.Text);

以下是我的 Json 序列化字符串

{
   "SelectedId":{"0":"ABCD","1":"JKLM"},
   "SelectedControlClientId":"YTUTOOO",
   "GroupTypeId":3,
   "SectionTypeId":"1"
}

引号转义字符串

"{\"SelectedId\":{\"0\":\"ABCD\",\"1\":\"JKLM\"},\"SelectedControlClientId\":\"YTUTOOO\",\"GroupTypeId\":3,\"SectionTypeId\":\"1\"}"

我的问题是选定的 Id 是 testWH 对象的数组。但是当我尝试反序列化它时,作为列表的 PassData 的 SelectedId 属性没有被序列化并且计数保持为零。

我尝试使用数组而不是列表,它给出了一个异常“no parameterless constructor...”

谁能解释我在这里做错了什么?

【问题讨论】:

  • 看不懂。代码字段/字段初始化器是什么意思?
  • 啊,抱歉 - 那只是我粘贴时的 IDE 插件改变了一些东西

标签: c# asp.net json asp.net-ajax


【解决方案1】:

这里的关键问题是 JSON 与您构建的对象不匹配。您可以通过编写您想要的数据并序列化来看到这一点:

var obj = new PassData
{
    SelectedId = new List<testWh>
    {
        new testWh { Id = "ABCD"},
        new testWh { Id = "JKLM"}
    },
    GroupTypeId = "3",
    SectionTypeId = "1",
    SelectedControlClientId = "YTUTOOO"
};
string jsonString = serializer.Serialize(obj);

它给出了类似的 JSON:

{"SelectedId":[{"Id":"ABCD"},{"Id":"JKLM"}],
 "SelectedControlClientId":"YTUTOOO","GroupTypeId":"3","SectionTypeId":"1"}

所以现在您需要决定要更改哪个; JSON 或类。以下替代类适用于您的原始 JSON,例如:

public class PassData
{
    public Dictionary<string,string> SelectedId { get; set; }
    public string SelectedControlClientId { get; set; }
    public string GroupTypeId { get; set; }
    public string SectionTypeId { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多