I'm facing an issue where I have a JSON serialized class that I am trying to deserialize into an object.
For example:
public class ContentItemViewModel
{
public string CssClass { get; set; }
public MyCustomClass PropertyB { get; set; }
}
The simple property (CssClass) can be deserialized using:
var contentItemViewModels = ser.Deserialize<ContentItemViewModel>(contentItems);
However, there is an error when deserializing PropertyB...
We tried adding a JavaScriptConverter:
ser.RegisterConverters(new List<JavaScriptConverter>{ publishedStatusResolver});
But when we specified 'MyCustomClass' as a 'SupportedType', the Deserialize method was not called. However, when we specified ContentItemViewModel as the SupportedType, then Deserialize was called.
Currently, our solution involves creating a custom converter like this:
class ContentItemViewModelConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
var cssClass = GetString(dictionary, "cssClass");
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)
};
}
}
}
However, we are looking for a simpler solution to only deserialize MyCustomClass without having to modify the converter each time a property is added or changed on the ViewModel.
Is there a way to just Deserialize PropertyB of type MyCustomClass?
Thank you for your assistance!