using Newtonsoft.Json.Linq;
public static void Main()
Title = "Attribute To JSON",
Content = @"<div><p>This blog is still not implemented</p></div>"
var str = JsonConvert.SerializeObject(blog);
[JsonConverter(typeof(ComplexTypeConverter))]
[ComplexAttribute(Type = "String", DisplayName = "Blog Title")]
public string Title { get; set; }
[ComplexAttribute(Type = "HTML")]
public string Content { get; set; }
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ComplexAttribute : System.Attribute
public string Type { get; set; }
public string DisplayName { get; set; }
public class ComplexTypeConverter : JsonConverter
public override bool CanConvert(Type objectType)
return (typeof(iComplexType).IsAssignableFrom(objectType));
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
object rootObject = Activator.CreateInstance(objectType);
JToken objJSON = JToken.ReadFrom(reader);
foreach (var token in objJSON)
PropertyInfo propInfo = rootObject.GetType().GetProperty(token.Path, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
var tk = token as JProperty;
JValue val = tk.Value.SelectToken("value") as JValue;
propInfo.SetValue(rootObject, Convert.ChangeType(val.Value, propInfo.PropertyType.UnderlyingSystemType), null);
propInfo.SetValue(rootObject, Convert.ChangeType(tk.Value, propInfo.PropertyType.UnderlyingSystemType), null);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
var type = value.GetType();
foreach (PropertyInfo propInfo in type.GetProperties())
object propVal = propInfo.GetValue(value, null);
var cutomAttribute = propInfo.GetCustomAttribute<ComplexAttribute>();
if (cutomAttribute != null)
jo.Add(propInfo.Name, JToken.FromObject(new { type = cutomAttribute.Type, displayname = cutomAttribute.DisplayName ?? propInfo.Name, value = propVal ?? string.Empty }, serializer));
jo.Add(propInfo.Name, JToken.FromObject(propVal ?? string.Empty, serializer));