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.
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