Serializing strings containing apostrophes with JSON.Net

后端 未结 4 1130
我在风中等你
我在风中等你 2020-12-03 10:47

I am using JSON.Net as my serializer for a large MVC 3 web application in c# and the Razor view engine. For the initial page load in one view, there is a large amount of JSO

4条回答
  •  一生所求
    2020-12-03 11:02

    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();
            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());
    

提交回复
热议问题