内容简介:显然,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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。