我正在尝试使用JavaScriptSerializer从JSON字符串反序列化以下类的实例:
public class Filter
{
public HashSet<int> DataSources { get; set; }
}
这是我正在尝试的代码:
以下是正在测试的代码:
Filter f = new Filter();
f.DataSources = new HashSet<int>(){1,2};
string json = (new JavaScriptSerializer()).Serialize(f);
var g= (new JavaScriptSerializer()).Deserialize<Filter>(json);
出现以下错误:
无法将类型为 'System.Collections.Generic.List
1[System.Int32]' 的对象转换为类型 'System.Collections.Generic.HashSet
1[System.Int32]'。
显然,序列化程序无法从JSON表示中区分列表和集合。 有什么解决方法?
注意:由于工作限制,我更喜欢避免使用外部库。
DataContractJsonSerializer
表现很好。谢谢! - David Sherret