URL JSONObject 问题

URL issue with JSONObject

我有以下代码,但是当我在数据库中保存低于 JSON 时,它给了我错误的 url 就像 {"#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());
    }
}

我想要url喜欢{"#url#":"https://www.test.com/test"} 请建议如何修复它?

尝试用单引号引用字符串,像这样

    JSONObject msgJson = new JSONObject();
    msgJson.put("#url#", "\'"+url+"\'");
    System.out.println(msgJson.toString());

您正在使用 org.json.simple JSON 库。 JSON-简单地从字符串中转义字符。 你不能改变这个东西,因为它不可配置。

但是你可以使用 org.json JSON 库,这不会转义字符串,好的部分是,你不必更改你的代码,现有的语法可以正常工作。

例如

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());
    }
}

输出:{"#url#":"https://www.test.com/test"}

尝试将斜杠 (/) 替换为 unicode 字符 \u2215,然后再将其传递给 JSON 对象。

解决方法如下:

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();
    }
}

这给出了正确的输出,只需 运行 这个代码。这将在数​​据库中存储准确的值。

{"#url#":"https://www.test.com/test"}