Umbraco Archetype Model Converter

Extension method and type converter for converting Archetype content into a list of custom objects.

Extension method for ArchetypeFieldsetModel.

public static class ArchetypeExtensions
{
  public static T As<T>(this ArchetypeFieldsetModel fieldset)
  {
    var instance = Activator.CreateInstance<T>();
    var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
      .Where(prop => !Attribute.IsDefined(prop, typeof(JsonIgnoreAttribute)));
      
    foreach (var propInfo in properties)
    {
      var attributes = propInfo.GetCustomAttributes(true);
      var jsonPropAttribute = (JsonPropertyAttribute)attributes.FirstOrDefault(attr => attr is JsonPropertyAttribute);
      
      var propertyAlias = jsonPropAttribute != null ? jsonPropAttribute.PropertyName : propInfo.Name;
      var propertyType = propInfo.PropertyType;
      
      if (!fieldset.HasProperty(propertyAlias) && !fieldset.HasValue(propertyAlias))
        continue;
        
      propInfo.SetValue(instance, fieldset.GetType().GetMethods()
        .First(m => m.IsGenericMethod && m.Name.Equals("GetValue"))
        .MakeGenericMethod(propertyType)
        .Invoke(fieldset, new object[] { propertyAlias }));
    }
  
    return instance;
  }
}

Archetype list type converter.

public class ArchetypeListConverter<T> : TypeConverter where T : class
{
  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  {
    if (sourceType == typeof(ArchetypeModel))
      return true;
      
    return base.CanConvertFrom(context, sourceType);
  }
  
  
  public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  {
    var items = new List<T>();
    
    if (value is ArchetypeModel)
    {
      foreach (var fieldset in (value as ArchetypeModel))
      {
        items.Add(fieldset.As<T>());
      }
    }
    
    return items;
  }
}