小编典典

使用JavaScriptSerializer序列化字典

json

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


阅读 299

收藏
2020-07-27

共1个答案

小编典典

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

希望这可以帮助!

2020-07-27