using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
public static void Main()
Description = @"<p class=""intro"">Bada Boom Bada Bing</p>"
var settings = new JsonSerializerSettings
ContractResolver = new CustomResolver(),
Formatting = Formatting.Indented
string json = JsonConvert.SerializeObject(foo, settings);
public string Name { get; set; }
public string Description { get; set; }
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);
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)
targetProperty.SetValue(target, (string)value);
public object GetValue(object target)
string value = (string)targetProperty.GetValue(target);
return HttpUtility.HtmlEncode(value);
public static class HttpUtility
public static string HtmlEncode(string s)
s = s.Replace("\u0026", "\u0026amp;")
.Replace("<", "\u0026lt;")
.Replace(">", "\u0026gt;")
.Replace("\"", "\u0026quot;");