使用 JSON.Net 序列化包含撇号的字符串 [英] Serializing strings containing apostrophes with JSON.Net

查看:25
本文介绍了使用 JSON.Net 序列化包含撇号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JSON.Net 作为我的序列化程序,用于 c# 和 Razor 视图引擎中的大型 MVC 3 Web 应用程序.对于一个视图中的初始页面加载,使用 @Html.Raw(JsonConvert.SerializeObject(myObject)) 将大量 JSON 转储到脚本标签内.

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 JSON dumped inside a script tag using @Html.Raw(JsonConvert.SerializeObject(myObject)).

问题是某些对象的某些值包含撇号(想想像 O'Brien 这样的名字),JSON.Net 不会以任何方式对其进行转义或编码.

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.

预编码存储在数据库中的值不是一种选择,因为这会使各种其他过程变得非常复杂.

It's not an option to pre-encode the values stored in the database because that vastly complicates various other processes.

有没有办法强制 JSON.Net 对其序列化的对象的值进行 HTML 编码,与调用 JavaScriptSerializer.Serialize(myObject) 时内置 JavaScriptSerializer 的方式相同?或者,有没有办法在视图中处理这个?

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)? Or, is there a way to deal with this in the view?

推荐答案

尽管在某些情况下,您可能希望将一些 JSON 作为 JavaScript 字符串或 HTML 属性值放入您的页面中,但最常见的是do 只是将它直接包含到 JavaScript 源代码中,因为 JSON 毕竟是有效的 JavaScript 语法.

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.

这篇关于使用 JSON.Net 序列化包含撇号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆