gpt4 book ai didi

asp.net - JSON 数据中的 "<"字符被序列化为\u003c

转载 作者:行者123 更新时间:2023-12-02 10:19:12 31 4
gpt4 key购买 nike

我有一个 JSON 对象,其中一个元素的值是一个字符串。该字符串中有字符 "<RPC>" 。我获取整个 JSON 对象,并在 ASP.NET 服务器代码中执行以下操作来获取名为 rpc_response 的对象。并将其添加到 POST 响应中的数据中:

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
HttpContext.Current.Response.AddHeader("Cache-Control", "private, no-cache");
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
HttpContext.Current.Response.Write(serializer.Serialize(rpc_response));
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.StatusCode = 200;

对象被序列化后,我在另一端(不是 Web 浏览器)收到它,该特定字符串如下所示:\u003cRPC\u003e

如何防止这些(和其他)字符未正确编码,同时仍然能够序列化我的 JSON 对象?

最佳答案

字符正在被“正确”编码!1使用有效的JSON库来正确访问JSON数据 - 它是一个< em>有效 JSON编码。

转义这些字符可以防止通过 JSON 进行 HTML 注入(inject) - 并使 JSON 对 XML 友好。也就是说,即使 JSON 直接发出到 JavaScript(正如经常所做的那样,因为 JSON 是 JavaScript 的有效2子集),它也不能用于终止 <script>尽早元素,因为相关字符(例如 <> )是在 JSON 本身中编码的。

标准 JavaScriptSerializer 没有有能力改变这种行为。这种转义可能可以在 Json.NET 中配置(或不同)。实现 - 但是,这应该没关系,因为有效的 JSON 客户端/库必须理解 \u逃脱。

<小时/>

1 来自 RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON) ,

Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point ..

另请参阅C# To transform Facebook Response to proper encoded string (这也与JSON转义有关)。

2a rare case when this does not hold ,但忽略(或考虑)这一点..

关于asp.net - JSON 数据中的 "<"字符被序列化为\u003c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592283/

31 4 0