URL issue with JSONObject

2019-05-26 08:37发布

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?

4条回答
叼着烟拽天下
2楼-- · 2019-05-26 09:19

Try replacing slash(/) with unicode character \u2215 before passing it to JSON object.

查看更多
走好不送
3楼-- · 2019-05-26 09:31

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"} 
查看更多
【Aperson】
4楼-- · 2019-05-26 09:32

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

查看更多
做个烂人
5楼-- · 2019-05-26 09:38

try to quote the string with single quotes, something like this

    JSONObject msgJson = new JSONObject();
    msgJson.put("#url#", "\'"+url+"\'");
    System.out.println(msgJson.toString());
查看更多
登录 后发表回答