gpt4 book ai didi

c# - 使用 JavaScriptSerializer 序列化字典

转载 作者:太空狗 更新时间:2023-10-29 18:08:45 25 4
gpt4 key购买 nike

显然,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)\/"}

希望这对您有所帮助!

关于c# - 使用 JavaScriptSerializer 序列化字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6416950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com