How do I make the toString() of the JSONObject enc

2019-08-27 01:08发布

In Java (using for Android), here are the code lines:

org.json.JSONObject array = new org.json.JSONObject("{\"value\":\"aész\"");
System.out.println("RES: " + array.toString());

The output I want:

RES: {"value":"a\u00e9sz"}

When it is actually:

RES: {"value":"aész"}

How do I make the JSONObject toString() method return the JSON String encoded with unicode values in the UTF-8 special characters, like the json_encode(array("value", "aész"));

Thanks in advance.

3条回答
混吃等死
2楼-- · 2019-08-27 01:25

I suppose what you want is ISO-8859-1 encoding. Here is a good answer on that subject: Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-27 01:35

It sounds more like jar issue. JsonObject is the class used across various open source libraries. Download this jar json-rpc-1.0.jar

Try this:

JSONObject json = new JSONObject();
json.put("value", "aész");
System.out.println(json.toString());

produces :

{"Name":"u00e9sz"}
查看更多
再贱就再见
4楼-- · 2019-08-27 01:36

You need to build your own version of the org.json.JSONObject class if you want it to escape all non-ASCII characters.

The signature of the method you need to modify is

 public static Writer quote(String string, Writer w) throws IOException

it is declared inside JSONObject.java. It is the method responsible of formatting all string values inside the produced json strings. it loops over all the characters of the source string and emits the corresponding output characters.

What you are looking for is in the "default" section of the switch statement.

the original code (at least in the sources I am watching right now) looks like this:

    default:
        if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
                || (c >= '\u2000' && c < '\u2100')) {
            w.write("\\u");
            hhhh = Integer.toHexString(c);
            w.write("0000", 0, 4 - hhhh.length());
            w.write(hhhh);
        } else {
            w.write(c);
        }

you need to change the "if" test to match all the characters you want to be escaped.

this does what you want:

    default:
        if (c < ' ' || c >= '\u0080') {
            w.write("\\u");
            hhhh = Integer.toHexString(c);
            w.write("0000", 0, 4 - hhhh.length());
            w.write(hhhh);
        } else {
            w.write(c);
        }

Hope this helps.

P.S: I run into your question because I met your same problem: the json strings I am generating need to travel through a system that accepts only ascii characters and mangles any character >127.

查看更多
登录 后发表回答