URL issue with JSONObject

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 20:38:20

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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!