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

标签 java json escaping backslash slash

我通过 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"}
 ]

当我们将 map 传递给 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 库一起使用。

关于Java/JSON.simple - 在斜杠之前打印反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51704124/

相关文章:

java - c :forEach issue when part of javascript function

java - NetBeans 插件 - 对用户保存代码执行操作

java - 将 json 数据传递给 spring-boot 应用程序的 Curl POST 命令不起作用

java - 如何让 jackson 不使用默认值序列化原语

c# - 返回一个已经从 WCF 格式化为 JSON 的字符串

bash - 我怎样才能告诉 bash 正确转义扩展字符串?

mysql - 如何在 VB.net 中为 SQL 编码字符串

C++ 样式编译器指令的 Java 解决方案

java - HTML 表单 Action Java

mysql - 如何使用 JDBC 在 MySQL 中转义反斜杠?