小编典典

如何强制JSON-lib的JSONObject.put(..)转义包含JSON的字符串?

json

使用JSON-lib时JSONObject,如何阻止该put方法存储包含JSON的字符串作为JSON而不是转义字符串?

例如:

JSONObject obj = new JSONObject();
obj.put("jsonStringValue","{\"hello\":\"world\"}");
obj.put("naturalStringValue", "\"hello world\"");
System.out.println(obj.toString());
System.out.println(obj.getString("jsonStringValue"));
System.out.println(obj.getString("naturalStringValue"));

印刷品:

{"jsonStringValue":{"hello":"world"},"naturalStringValue":"\"hello world\""}
{"hello":"world"}
"hello world"

我希望它打印:

{"jsonStringValue":"{\"hello\":\"world\"}","naturalStringValue":"\"hello world\""}
{"hello":"world"}
"hello world"

是的,我意识到这很令人讨厌。但是,这是为了支持JSON序列化管道,出于互操作性的考虑,这是预期的行为。在某些情况下,我们会序列化可能是/包含有效JSON的用户输入。我们不希望用户输入成为将输入序列化的JSON对象的一部分。

手动转义不起作用,因为它会导致JSON-lib转义\字符:

JSONObject obj = new JSONObject();
obj.put("naturalJSONValue","{\"hello\":\"world\"}");
obj.put("escapedJSONValue", "{\\\"hello\\\":\\\"world\\\"}");
System.out.println(obj.toString());
System.out.println(obj.getString("naturalJSONValue"));
System.out.println(obj.getString("escapedJSONValue"));

输出:

{"naturalJSONValue":{"hello":"world"},"escapedJSONValue":"{\\\"hello\\\":\\\"world\\\"}"}
{"hello":"world"}
{\"hello\":\"world\"}

此时,任何启用手动选择性转义复杂JSON对象的变通办法都将完全否定使用JSON-lib的价值。

另外,我知道以前曾有人问这个问题,但是很遗憾,我不能轻易接受它的回答。JSON-
lib在我的项目的许多领域中都是使用率很高的依赖项,而将其换出将是一项艰巨的任务。我必须绝对确定,在可以交换到Jackson,simple-
json或Gson之前,无法使用JSON-lib实现此目标。


阅读 840

收藏
2020-07-27

共1个答案

小编典典

使用单引号将字符串引起来。从文档中

字符串可以用’(单引号)引起来。

如果字符串不以引号或单引号开头,并且不包含前导或尾随空格,并且不包含以下任何字符,则根本不需要引号:{} [] / \: ,=;
#,如果它们看起来不像数字,并且不是保留字true,false或null。

因此,修改您的示例:

net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
obj.put("jsonStringValue","{\"hello\":\"world\"}");
obj.put("quotedJsonStringValue","\'{\"hello\":\"world\"}\'");
obj.put("naturalStringValue", "\"hello world\"");
System.out.println(obj.toString());
System.out.println(obj.getString("jsonStringValue"));
System.out.println(obj.getString("quotedJsonStringValue"));
System.out.println(obj.getString("naturalStringValue"));

产生:

{"jsonStringValue":{"hello":"world"},"quotedJsonStringValue":"{\"hello\":\"world\"}","naturalStringValue":"\"hello world\""}
{"hello":"world"}
{"hello":"world"}
"hello world"

请注意,如何quotedJsonStringValue将其视为字符串值而非JSON,并在输出JSON中用引号引起来。

2020-07-27