来自 java/webservice(json) 的字符串中的空白 space 会产生不同的字节数组

blank space in strings from java/webservice(json) yields different byte arrays

我目前正在为 jersey 2-0 网络服务 (json) 编写一些验收测试,然后再重构项目中的某些方法,我偶然发现了断言 blank-space 字符串的问题网络服务。

我从我的网络服务中得到以下输出:

"Boxes": [
    {
        "id": 1,
        "title": " ", //Yes this is a white-space
        "genre": "genre",
        "info": "some info",
        "rating": "3",
        "artist": "Artist 1"
    }
],

然后我将我的响应从网络服务转换为 JSONObject,如下所示:

public static JSONObject responseToJsonObject(HttpResponse httpResponse) throws IOException {
    String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
    return new JSONObject(responseString);
}

然后在我的测试中,是像这样做正常的断言:

//* http request creation omitted *//
JSONObject jsonResponse = JsonTranslator.responseToJsonObject(httpRequest)
JSONArray boxes = jsonResponse.getJSONArray("boxes ");
JSONObject result = boxes .getJSONObject(0);

assertEquals(" ", result.getString("title"));

问题是最后一个断言失败了。

org.junit.ComparisonFailure: 
Expected : 
Actual   : 

我大概知道为什么,字节数组会产生两种不同的结果。一个字节为 [32](在 java 中创建的字节),而来自网络服务的字节为 [-62,-96]

我以前从未遇到过这个问题。如果我尝试在 EntityUtils 方法中不使用 "UTF-8" 进行转换,我会得到更糟糕的结果(  字节数组:[-61,-126,-62,-96]

我可以看到我的网络服务的 content-type header 已正确设置为 application/json

谁能解释一下这里发生了什么?

您到达那里的角色不是 "normal" space。这是一个不间断的 space。 HTML 中的相同字符将用   描述。

它的 unicode 值为 '\u00A0'。它的 UTF-8 表示形式是 C2 A0,这就是您在字节数组中得到的内容。

我相信如果您尝试以下断言它会起作用:

assertEquals("\u00A0", result.getString("title"));