Reputation: 87
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String path = "/folder1/folder2".replaceAll("/","\\\\/");//for get \/folder1\/folder2
String result = gson.toJson(path);
and the result is \\/folder1\\/folder2
Upvotes: 0
Views: 2896
Reputation: 1500485
Your path contains backslashes, and those are being escaped by toJson()
. When you deserialize at the other end, you'll end up with a string of \/folder1\/folder2
via normal JSON unescaping. I don't see this as an issue: the aim of serialization is that you get the same data out at the far end as you put in this end. Your input is \/folder1\/folder2
, and so is your output - the fact that that requires escaping along the way is irrelevant.
It does raise the question as to why you want \/
in the string at all though. Are you trying to escape the forward slashes manually? You don't need to do that. I strongly suspect you should just have /folder1/folder2
without any replacement.
EDIT: From the comments, it looks like you have a requirement you don't even understand to escape /
. While it turns out that that it's valid to escape any character in JSON, the requirement of escaping /
is distinctly non-standard, and I suspect you'll have a hard time finding a JSON library which allows you to say that you need it to be escaped.
I suggest you revisit whatever is imposing this requirement on you, and try to fix it so that it accepts standard JSON without escaping the /
. Trying to add the extra level of escaping manually will not work.
Upvotes: 2