Serializing strings containing apostrophes with JSON.Net

后端 未结 4 1116
我在风中等你
我在风中等你 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<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());
    
    0 讨论(0)
  • 2020-12-03 11:03

    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.

    0 讨论(0)
  • 2020-12-03 11:04
    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        StringEscapeHandling = StringEscapeHandling.EscapeHtml
    };
    
    JsonConvert.SerializeObject(obj, settings);
    
    0 讨论(0)
  • 2020-12-03 11:07

    Use System.Web.HttpUtility.HtmlEncode

    HttpUtility.HtmlEncode(JsonConvert.SerializeObject(myObject))
    
    0 讨论(0)
提交回复
热议问题