【发布时间】:2011-12-23 13:21:59
【问题描述】:
我有一个已序列化为 JSON 的类,我正在尝试将其反序列化为一个对象。
例如
public class ContentItemViewModel
{
public string CssClass { get; set; }
public MyCustomClass PropertyB { get; set; }
}
简单属性 (CssClass) 将反序列化:
var contentItemViewModels = ser.Deserialize<ContentItemViewModel>(contentItems);
但是 PropertyB 出错了...
我们添加了一个 JavaScriptConverter:
ser.RegisterConverters(new List<JavaScriptConverter>{ publishedStatusResolver});
但是当我们将“MyCustomClass”添加为“SupportedType”时,从未调用过 Deserialize 方法。但是,当我们将 ContentItemViewModel 作为 SupportedType 时,就会调用 Deserialize。
我们有一个看起来像这样的当前解决方案:
class ContentItemViewModelConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
var cssClass = GetString(dictionary, "cssClass"); //I'm ommitting the GetString method in this example...
var propertyB= GetString(dictionary, "propertyB");
return new ContentItemViewModel{ CssClass = cssClass ,
PropertyB = new MyCustomClass(propertyB)}
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new Exception("Only does the Deserialize");
}
public override IEnumerable<Type> SupportedTypes
{
get
{
return new List<Type>
{
typeof(ContentItemViewModel)
};
}
}
}
但我们更喜欢仅反序列化 MyCustomClass 的更简单的解决方案,因为 ViewModel 上还有许多其他字段,每次更改/添加属性时都必须编辑此转换器似乎很浪费。 ...
有没有办法反序列化 MyCustomClass 类型的 JUST PropertyB?
感谢您的帮助!
【问题讨论】:
标签: c# javascript json serialization