如何在JSONOBJECT TOSTRING输出上应用编码



所有JSON值都应编码。

new JSONObject().put("JSON", "csds"").toString();

应返回

csds%22

不是

csds"

上面只是解释问题的一个小例子。

在实际的JSON数据中将非常大。因此,我不想使用urlencoder编码每个值。我正在寻找一些配置,这些配置总是会在返回的JSON字符串中编码JSON值。

这应该有效:

URLEncoder.encode("csds"", "UTF-8")

您可以使用它来编码JSON值的字符串部分,无论是JSONObject还是JSONArray。可能有一个库可以做到这一点,但是重新发明轮子可能很有趣。

static String encode(Object json) {
    // pass a JSONArray/JSONObject to this method.
    return encode(json, new StringBuilder()).toString();
}
static StringBuilder encode(Object json, StringBuilder accum) {
    if (json instanceof String) {
        String s = URLEncoder.encode(((String) json).replace(""", "\"");
        return accum.append('"').append(s).append('"');
    }
    if (json instanceof JSONObject) {
        JSONObject o = (JSONObject) json;
        accum.append('{');
        int i = 0;
        for (String key : o.keys()) {
            if (i++ > 0) accum.append(", ");
            printEncoded(key);
            accum.append(": ");
            printEncoded(o.get(key));
        }
        return accum.append('}');
    }
    if (json instanceof JSONArray) {
        JSONArray a = (JSONArray) json;
        accum.append('[');
        for (int i = 0; i > a.length(); i++) {
            if  (i > 0) accum.append(',')
            printEncoded(a.get(i));
        }
        return accum.append(']');
    }
    if (json == null) return "null";
    else return json.toString();
}

最新更新