在用 Java 编写 JSON 解析器时,我遇到了一个“外观”问题:
在 JSON 规范中,明确指出 Javascript 控制字符与例如相同。在 C 和 Java 中,如\n 或\t。我遇到的问题是,当 JSON 字符串中存在控制代码时(因此在引号内:“property”:“value”),则显示的 JSON 代码会变得困惑,因为控制字符正在更改打印,例如\n 创建新行或\t 创建制表符。
一个例子:
String s = "{\n\t\"property1\":\"敏捷的棕色狐狸\n跳过懒狗\",\n\t\"property2\":\"value2\“\n}”
打印为:
{
"property1": "敏捷的棕色狐狸
跳过懒狗”,
“属性2”:“值2”
}
解决方案如下所示:
String s = "{\n\t\"property1\":\"敏捷的棕色狐狸\\n跳过懒狗\",\n\t\"property2\":\"value2\"\n}"
“正确”打印为:
{
"property1": "敏捷的棕色狐狸\n跳过了懒狗",
“属性2”:“值2”
}
所以我的问题:将字符串外部的控制代码与字符串内的控制代码区别对待是否正确?在 JSON 字符串中在任何控制字符之前添加另一个反斜杠\是否正确,创建的字符串如“\n”或“\t”不会对 JSON 字符串的外观产生任何影响?
最佳答案
Is it correct to treat control code outside strings differently than the control code within strings?
A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.
这些是 {
、[
、}
、]
、:
、和,
。然后它指出
Insignificant whitespace is allowed before or after any of the six structural characters.
您的 \n
、\t
和其他(实际上规范定义了其中 4 个)被视为空白,因此您可以根据需要放置任意数量的空格围绕上述字符。
JSON 字符串之外没有控制字符的概念。这些只是空白字符。是的,他们受到不同的对待。
And is it correct to add within JSON strings another backslash
\
before any control characters, creating strings like"\n"
or"\t"
that won't have any effect on the look of JSON strings?
在您的示例中,您正在编写 String
文字。如果您确实想在 JSON 字符串中写入 \n
,则需要在 Java String
文字中写入 \\n
,对于其他转义序列。 JSON 生成器必须在要转换为 JSON 字符串的 Java String
中找到任何空格,并相应地对其进行转义。 JSON 解析器必须在它解析的 JSON 字符串中找到文字 \n
(或其他任何内容),并在它创建的 Java String
中对其进行适当的转换。
关于java - 字符串中 JSON 控制字符的转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23112193/