爬蟲取得的回應內容為 JSON 字串,其中中文已被 Unicode 轉義 (如 \u975e\u5e38\u4e0d\u9519 → 「非常不錯」)。許多開發者誤以為需手寫正則或解碼器還原,**實則標準 JSON 庫 (org.json、Jackson、Gson) 解析時會自動將 \uXXXX 轉為對應字元**,無需額外處理。
{
"errno": 0,
"data": {
"hasmore": true,
"comments": [
{
"user_name": "Fei52012345",
"text": "\u975e\u5e38\u4e0d\u9519\u7684\u4e00\u7bc7\u6587\u7ae0\uff0c\u5e72\u8d27\uff0c\u5e72\u8d27\u3002\u628a\u793e\u4ea4\u8fd0\u8425\u8bb2\u7684\u900f\u5f7b\u3002",
"from": "weibo"
}
]
}
}
import org.json.*;
public class JsonUnicodeDemo {
public static void main(String[] args) {
String jsonStr = "..."; // 上述 JSON 字串
JSONObject root = new JSONObject(jsonStr);
int errno = root.getInt("errno");
JSONObject data = root.getJSONObject("data");
boolean hasMore = data.getBoolean("hasmore");
JSONArray comments = data.getJSONArray("comments");
for (int i = 0; i < comments.length(); i++) {
JSONObject comment = comments.getJSONObject(i);
String user = comment.getString("user_name");
// 關鍵點:getString() 直接返回已解碼的中文字串!
String text = comment.getString("text");
String from = comment.getString("from");
System.out.println("用戶: " + user);
System.out.println("內容: " + text); // 輸出: 非常不錯的一篇文章,干貨,干貨。把社交運營講的透徹。
System.out.println("來源: " + from);
System.out.println("---");
}
}
}
JSON 標準 (RFC 8259) 規定:字串中的 \uXXXX 為 **Unicode 碼點轉義序列**,解析器**必須**在解析階段將其轉為對應 Unicode 字元。org.json.JSONTokener 內部即實現此邏輯,getString() 回傳的 java.lang.String 已為正確 UTF-16 字元序列。
| 庫 | Maven 依賴 | 關鍵 API | 特點 |
|---|---|---|---|
| org.json | org.json:json:20231013 | new JSONObject(str) | 極輕量、JDK 內建風格、適合簡單解析 |
| Jackson | com.fasterxml.jackson.core:jackson-databind | mapper.readTree(str) / mapper.readValue(str, Class) | 高效能、支援 POJO 綁定、企業級首選 |
| Gson | com.google.code.gson:gson | gson.fromJson(str, Type) | API 簡潔、對 Kotlin 友善、Android 常用 |