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

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

问题描述

我使用JSON.Net作为我的序列化在C#中的大MVC 3 Web应用程序和的Razor视图引擎。在一个视图中的初始页面加载,有一个使用 @ Html.Raw(JsonConvert.SerializeObject(myObject的)) script标签内倾倒大量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)).

的问题是,一些对象的一些值包含撇号(认为像奥布莱恩名称),其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.

这不是一个选项,以pre-CN code存储在数据库中的值,因为这大大各种其他进程复杂化。

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

有没有办法强制JSON.Net到HTML EN code,它序列化的方式,相同的对象的值内置的JavaScriptSerializer当你调用确实 JavaScriptSerializer.Serialize (myObject的)?或者说,有没有办法来处理这​​个视图?

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属性值,通常你会做的仅仅是包括其直接插入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天全站免登陆