Java/JSON.simple-在斜杠之前打印反斜杠



我正在通过Java和json.simple库将一些数据打印到json文件中,但每当有斜杠时,我都会添加一个反斜杠,如中所示

"thing":[
{"file":"Screenshot_from_2018-07-12_14-41-19.png",
"currentDateTime":"02/08/2018 15:11:14",
"selectedDate":"02/08/2018",
"uri":"/var/stuff/files/Screenshot_from_2018-07-12_14-41-19.png",
"user":"user"}
]

它发生在我们将地图传递给JSONObject:的时刻

map.put("file", fileNameFormat);
map.put("uri", filesPath + "/" + service + "/" + fileNameFormat);
map.put("user", user);
map.put("selectedDate", selectedDate);
map.put("currentDateTime", currentDateTime);
JSONObject json = new JSONObject(map); //HERE

我认为当我进一步开发这个实用程序时,这将是一个问题。为什么会发生这种情况,我该如何绕过它?提前谢谢。

您可以使用GSON库来实现这一点。

例如,

HashMap<String, String> map = new HashMap<>();
map.put("file", "file");
map.put("uri", "Your_filesPath" + "/" + "Your_service" + "/" + "Your_fileNameFormat");
map.put("user", "user");
map.put("selectedDate", "selectedDate");
map.put("currentDateTime", "currentDateTime");
Gson gson = new Gson(); 
String json = gson.toJson(map); 
System.out.println(json);

放置GSON依赖项并希望这与GSON库一起工作。

这样做是为了允许在脚本标记中使用json字符串,正如这个问题所解释的:

JSON:为什么要转义正向斜杠?

在javascript方面,它将按预期读取
'/' === '/'在JavaScript中,JSON是有效的JavaScript。

为了处理Java中的所有内容,可以使用Gson。请查看使用Gson将Json转换为对象的链接:Json转换成Java对象

JSON.simple遵循JSON规范RFC4627。斜线和其他各种控制序列都应转义。

这不会以任何方式限制您的应用程序,因为JavaScript会将其识别为简单的"/"。

最新更新