我有一個已經序列化成JSON的類,並且我試圖將其反序列化爲一個對象。c#JavaScriptConverter - 如何反序列化自定義屬性?
例如
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一個簡單的解決方案,因爲有一些其他領域的這些都對視圖模型,每次我們更改/添加屬性時,編輯此轉換器似乎是一種浪費......
是否有反序列化類型MyCustomClass的JUST PropertyB的方法?
感謝您的幫助!