使用JavaScriptSerializer序列化字典

使用JavaScriptSerializer序列化字典,第1张

使用JavaScriptSerializer序列化字典

尽管我同意JavascriptSerializer是胡扯,而Json.Net是更好的选择,但是您可以通过一种方法使JavascriptSerializer序列化所需的方式。您将必须注册一个转换器,并使用如下方法覆盖Serialize方法:

    public class KeyValuePairJsonConverter : JavascriptConverter{    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavascriptSerializer serializer)    {        var instance = Activator.CreateInstance(type);        foreach (var p in instance.GetType().GetPublicProperties())        { instance.GetType().GetProperty(p.Name).SetValue(instance, dictionary[p.Name], null); dictionary.Remove(p.Name);        }        foreach (var item in dictionary) (instance).Add(item.Key, item.Value);        return instance;    }    public override IDictionary<string, object> Serialize(object obj, JavascriptSerializer serializer)    {        var result = new Dictionary<string, object>();        var dictionary = obj as IDictionary<string, object>;        foreach (var item in dictionary) result.Add(item.Key, item.Value);        return result;    }    public override IEnumerable<Type> SupportedTypes    {        get        { return new ReadOnlyCollection<Type>(new Type[] { typeof(your_type) });        }    }}JavascriptSerializer javascriptSerializer = new JavascriptSerializer();javascriptSerializer.RegisterConverters(new JavascriptConverter[] { new ExpandoJsonConverter() });jsonOfTest = javascriptSerializer.Serialize(test);// {"x":"xvalue","y":"/Date(1314108923000)/"}

希望这可以帮助!



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5477599.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存