简体   繁体   English

使用JSON.Net序列化包含撇号的字符串

[英]Serializing strings containing apostrophes with JSON.Net

I am using JSON.Net as my serializer for a large MVC 3 web application in c# and the Razor view engine. 我正在使用JSON.Net作为我在c#和Razor视图引擎中的大型MVC 3 Web应用程序的序列化程序。 For the initial page load in one view, there is a large amount of JSON dumped inside a script tag using @Html.Raw(JsonConvert.SerializeObject(myObject)) . 对于一个视图中的初始页面加载,使用@Html.Raw(JsonConvert.SerializeObject(myObject))在脚本标记内转储了大量JSON。

The problem is that some values of some objects contain apostrophes (think names like O'Brien), which JSON.Net is not escaping or encoding in any way. 问题是某些对象的某些值包含撇号(想想像O'Brien这样的名字),JSON.Net没有以任何方式转义或编码。

It's not an option to pre-encode the values stored in the database because that vastly complicates various other processes. 对预存储在数据库中的值进行预编码不是一种选择,因为这会使各种其他进程复杂化。

Is there a way to force JSON.Net to HTML encode the values of the objects that it serializes, the same way that the built-in JavaScriptSerializer does when you call JavaScriptSerializer.Serialize(myObject) ? 有没有办法强制JSON.Net对HTML序列化对象的值进行编码,就像调用JavaScriptSerializer.Serialize(myObject)时内置的JavaScriptSerializer一样? Or, is there a way to deal with this in the view? 或者,有没有办法在视图中处理这个问题?

JsonSerializerSettings settings = new JsonSerializerSettings
{
    StringEscapeHandling = StringEscapeHandling.EscapeHtml
};

JsonConvert.SerializeObject(obj, settings);

You can create custom JsonConverter like this: 您可以像这样创建自定义JsonConverter:

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: 要仅将此属性用于Name属性,请按属性指定:

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

To apply Converter to all strings use: 要将Converter应用于所有字符串,请使用:

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

虽然在某些情况下您可能希望将某些JSON作为JavaScript字符串或HTML属性值放入页面中,但大多数情况下您只需将其直接包含在JavaScript源代码中,因为JSON之后是有效的JavaScript语法所有。

使用System.Web.HttpUtility.HtmlEncode

HttpUtility.HtmlEncode(JsonConvert.SerializeObject(myObject))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM