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


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

查看所有标签

猜你喜欢:

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

Coming of Age in Second Life

Coming of Age in Second Life

Tom Boellstorff / Princeton University Press / 2008-04-21 / USD 29.95

The gap between the virtual and the physical, and its effect on the ideas of personhood and relationships, is the most interesting aspect of Boellstorff's analysis... Boellstorff's portrayal of a virt......一起来看看 《Coming of Age in Second Life》 这本书的介绍吧!

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

RGB HEX 互转工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具