【问题标题】:C#- JSON escape \n character to \\n characterC#- JSON 转义 \n 字符到 \\n 字符
【发布时间】:2022-01-03 16:55:01
【问题描述】:

我想将 JSON 中的 \n 字符替换为 \\n。我想这样做是因为我的 JSON 中的 \n 字符在我加载它的源中被解析为换行符(空格)。我希望它保留为文本字符-\n。使用另一个 \ 转义 \n 工作,即在我的 JSON 中将所有 \n 转换为 \\n。

所以我想找到实现这一目标的最佳方法。我在 C# 中使用 NewtonSoft JSON 库来序列化 JSON。在这个或其他一些 JSON SDK 中是否有任何方法可以用来转义 JSON 中的 \n 字符?

我拥有的 JSON-

{
        "Name": "KeyName",
        "Value": "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<tokens xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"abc.com">\n  <properties>\n    <property id=\"x\" range=\"true\">y</property>\n    <property id=\"x\" range=\"true\">y</property>\n     </properties>\n</tokens>"
}

从 JSON 转换后生成的文本文件-

KeyName|<?xml version="1.0" encoding="utf-16"?>
<tokens xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="abc.com">
  <properties>
    <property id="3" range="true">4</property>
    <property id="2" range="true">50</property>
  </properties>
</tokens>

我需要的文本文件-

KeyName|<tokens xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="abc.com">\n  <properties>\n    <property id="2" range="true">50</property>\n    <property id="3" range="true">1</property>\n </properties>\n</tokens>

JSON 中的这个 \n 正在产生问题,因为它在我生成的文本文件中被解析为新行,我需要它作为文本文件中的 '\n' 字符。请注意,我无法控制用于将 JSON 转换为文本的工具,但我可以更改 JSON 并将 JSON 中的 '\n' 更改为 '\\n' 是可行的,即它即将到来作为生成的文本文件中的“\n”。

【问题讨论】:

  • /n 被解析为一个新行有点奇怪,其中几乎所有内容都使用反斜杠作为转义字符,因此它将是 \n。但无论如何,最有效的方法就是json = json.Replace("/n", "//n");
  • 这是我的错误,它应该只是\n。编辑问题!谢谢
  • 好的,所以 json = json.Replace("\n", "\\n"),我认为你不需要/需要 HTML 转义
  • 我担心这个操作通过替换的性能成本,因为数据会很大。我希望可能有一个 JSON 编码属性或其他更有效的方法。
  • 然后在问题中添加上下文,并附上示例。

标签: c# json json.net escaping newline


【解决方案1】:

Newtonsoft documentation 说可以选择序列化转义不同的字符。

对于您的特殊情况,我认为您想使用EscapeHtml

【讨论】:

    猜你喜欢
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2021-12-09
    相关资源
    最近更新 更多