I've the following code, but when I am saving below JSON in database its giving me wrong url like {"#url#":"https:\/\/www.test.com\/test"}
import org.json.simple.JSONObject;
public class DemoURL {
private static String url = "https://www.test.com/test";
public static void main(String[] args) {
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", url);
System.out.println(msgJson.toString());
}
}
I want url like {"#url#":"https://www.test.com/test"}
Please suggest how to fix it?
Here is the solution:
public class App{
private static String url = "https://www.test.com/test";
public static void main(String[] args) {
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", url);
System.out.println(getCleanURL(msgJson.toString()));
}
private static String getCleanURL(String url){
return url.replaceAll("\\\\", "").trim();
}
}
This gives correct output, simply run this code. This will store exact value in the database.
{"#url#":"https://www.test.com/test"}
You are using org.json.simple
JSON library. JSON-Simple escapes char from String.
You can't change this thing, as its not configurable.
But you can use org.json
JSON library, this will not escape String, and good part is, you don't have to change your code, existing syntax will work fine.
e.g.
import org.json.JSONObject;
public class DemoURL {
private static String url = "https://www.test.com/test";
public static void main(String[] args) {
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", url);
System.out.println(msgJson.toString());
}
}
output : {"#url#":"https://www.test.com/test"}
Try replacing slash(/) with unicode character \u2215 before passing it to JSON object.
try to quote the string with single quotes, something like this
JSONObject msgJson = new JSONObject();
msgJson.put("#url#", "\'"+url+"\'");
System.out.println(msgJson.toString());
来源:https://stackoverflow.com/questions/35715155/url-issue-with-jsonobject