我的申请是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属性不会被序列化,并且计数保持为零。
我尝试使用数组而不是List,它给出了一个例外“没有参数少的构造函数......”
有人可以解释我在这里做错了吗?
答案 0 :(得分:2)
这里的关键问题是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; }
}