Serializing strings containing apostrophes with JSON.Net Serializing strings containing apostrophes with JSON.Net json json

Serializing strings containing apostrophes with JSON.Net


JsonSerializerSettings settings = new JsonSerializerSettings{    StringEscapeHandling = StringEscapeHandling.EscapeHtml};JsonConvert.SerializeObject(obj, settings);


Though there are some cases wherein you might want to drop some JSON into your page as a JavaScript string, or an HTML attribute value, most often what you'd do is simply include it directly into JavaScript source, because JSON is valid JavaScript syntax after all.


You can create custom JsonConverter like this:

public class EscapeQuoteConverter : JsonConverter {    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)     {        writer.WriteValue(value.ToString().Replace("'", "\\'"));    }    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)     {        var value = JToken.Load(reader).Value<string>();        return value.Replace("\\'", "'");    }    public override bool CanConvert(Type objectType)     {        return objectType == typeof(string);    }}

To use this only for Name property specify it by attribute:

public class Person {    [JsonConverter(typeof(EscapeQuoteConverter))]    public string Name { get; set; } }

To apply Converter to all strings use:

JsonConvert.SerializeObject(person, Formatting.Indented, new EscapeQuoteConverter());