C#-JSON转义符到\\n字符



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

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

我拥有的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"的形式出现。

Newtonsoft文档指出,您可以选择序列化转义的不同字符。

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

最新更新