c# – 使用JavaScriptSerializer序列化词典

栏目: ASP.NET · 发布时间: 7年前

内容简介:显然,IDictionary<string,object>被序列化为KeyValuePair对象的数组(例如,[{Key:“foo”,Value:“bar”},…]).是否可以将其序列化为对象(例如,{foo:“bar”})?翻译自:https://stackoverflow.com/questions/6416950/serializing-dictionaries-with-javascriptserializer

显然,IDictionary<string,object>被序列化为KeyValuePair对象的数组(例如,[{Key:“foo”,Value:“bar”},…]).是否可以将其序列化为对象(例如,{foo:“bar”})?

虽然我同意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)\/"}

希望这可以帮助!

翻译自:https://stackoverflow.com/questions/6416950/serializing-dictionaries-with-javascriptserializer


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Python

Programming Python

Mark Lutz / O'Reilly Media / 2006-8-30 / USD 59.99

Already the industry standard for Python users, "Programming Python" from O'Reilly just got even better. This third edition has been updated to reflect current best practices and the abundance of chan......一起来看看 《Programming Python》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具