0 Comments
Ditto is a great model mapper for Umbraco. It automatically map the properties to the object class properties which allows user to use strong-type object in the code. The idea behind the model mapper is to use reflection and custom attributes to map object for simple type properties (i.e. string, int etc). If you are not familiar with custom attributes, you can read a great article here. For a complex type (i.e. JObject), You can create a custom type converter to map the properties. However, the issue I was having is when converting the JObject into the class which has the custom type converter .

Issue:


I have a class with custom type converter LinkPickerTypeConverter

[TypeConverter(typeof(LinkPickerTypeConverter))]
public class LinkPicker
{
/// <summary>
/// Gets or sets the id.
/// </summary>
public int Id { get; set; }

/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }

/// <summary>
/// Gets or sets the url.
/// </summary>
public string Url { get; set; }

/// <summary>
/// Gets or sets the target.
/// </summary>
public string Target { get; set; }
}

In LinkPickerTypeConverter,I need to covert JObject to Link Picker. So I used the ToObject method to convert. i.e. json.ToObject<LinkPicker>();

However, because NewtonJson is using Type converter which is overwritten by my custom type converter, which causing the failing when covert JObject to the class.

Solution:


For walk around the issue, I just change ToObject method with Deserialize of JavaScriptSerializer.

var serializer = new JavaScriptSerializer();

serializer.Deserialize<LinkPicker>(value.ToString());

I figured out another better solution by dynamically assigning the JsonConverter.

TypeDescriptor.AddAttributes(typeof(LinkPicker), new TypeConverterAttribute(typeof(JsonConverter)));

After this, you can use ToObject method to convert the JObject to the custom class. i.e. value.ToObject<LinkPicker>();