0

I'm printing some data into a json file through Java and JSON.simple library, but I'm getting a backslash added whenever a ther's a slash as in:

"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"}
 ]

It happens at the moment when we pass the map on to the 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

I think it's going to be a problem when I further develop the utility. Why does it happen and how do I walk around it? Thanks in advance.

azro
  • 53,056
  • 7
  • 34
  • 70
LoloSSS
  • 91
  • 2
  • 12
  • There is no workaround possible in json-simple for this. They already have a bug open for this: http://code.google.com/p/json-simple/issues/detail?id=8 – S.K. Aug 06 '18 at 09:32

3 Answers3

2

You can use GSON Library for that.

For example,

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);

Put GSON dependency and Hope this works with GSON library.

bangoria anjali
  • 400
  • 1
  • 10
1

This is done to allow json strings inside scripts tags, as this question explains:

JSON: why are forward slashes escaped?

On the javascript side it will be read as intended.
'\/' === '/' in JavaScript, and JSON is valid JavaScript.

To handle everything in Java, Gson could be used. Please check the link to use Gson for converting Json to objects: Json to Java objects

bitsobits
  • 104
  • 11
  • Thanks for the info. This .json file is supposed to be worked by Java only, and it will be read by the Java program again at certain stage, so I'm worried this escaped slashes will be a problem when read. Is Java going to understand they are escaped slashes? – LoloSSS Aug 06 '18 at 09:39
  • You can use Gson for converting Json to java objects. – bitsobits Aug 06 '18 at 09:49
1

JSON.simple follows the JSON specification RFC4627. Both slashes and various other control sequences shall be escaped.

This does not limit your application in any way, as JavaScript will recognize it as a simple '/'.

iR0Nic
  • 320
  • 6
  • 11