using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
public static void Main()
""Name"" : ""<b>Foo Bar</b>"",
""Description"" : ""<p>Bada Boom Bada Bing</p>"",
JsonSerializerSettings settings = new JsonSerializerSettings
ContractResolver = new CustomResolver()
Foo foo = JsonConvert.DeserializeObject<Foo>(json, settings);
Console.WriteLine("Name: " + foo.Name);
Console.WriteLine("Desc: " + foo.Description);
public string Name { get; set; }
public string Description { get; set; }
class AllowHtmlAttribute : Attribute
public class CustomResolver : DefaultContractResolver
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in props.Where(p => p.PropertyType == typeof(string)))
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null && pi.GetCustomAttribute(typeof(AllowHtmlAttribute), true) == null)
prop.ValueProvider = new HtmlEncodingValueProvider(pi);
protected class HtmlEncodingValueProvider : IValueProvider
PropertyInfo targetProperty;
public HtmlEncodingValueProvider(PropertyInfo targetProperty)
this.targetProperty = targetProperty;
public void SetValue(object target, object value)
var encoded = AntiXssEncoder.HtmlEncode((string)value, useNamedEntities: true);
targetProperty.SetValue(target, encoded);
public object GetValue(object target)
return targetProperty.GetValue(target);
public static class AntiXssEncoder
public static string HtmlEncode(string s, bool useNamedEntities)
s = s.Replace("\u0026", "\u0026amp;").Replace("<", "\u0026lt;").Replace(">", "\u0026gt;");