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

时间:2018-08-06 09:09:05

标签: java json escaping backslash slash

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

"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

我认为,当我进一步开发该实用程序时,这将是一个问题。为什么会发生,我该如何解决?预先感谢。

3 个答案:

答案 0 :(得分:2)

您可以为此使用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库一起使用。

答案 1 :(得分:1)

这样做是为了允许在scripts标记内包含json字符串,如该问题所解释的:

JSON: why are forward slashes escaped?

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

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

答案 2 :(得分:1)

JSON.simple紧跟JSON specification RFC4627。斜杠和其他各种控制顺序都应转义。

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

相关问题