1.背景
有时候对接的接口返回的中文是unicode,这是我们需要将其转为中文
2.代码
/**
* unicode转为中中文
* @param unicodeEscapedString
*/
public void unicodeEscapeToChinese (String unicodeEscapedString) {
// 解码Unicode转义序列
StringBuilder decodedString = new StringBuilder();
int i = 0;
while (i < unicodeEscapedString.length()) {
if (unicodeEscapedString.startsWith("\\u", i)) {
// 找到一个Unicode转义序列
int codePoint = Integer.parseInt(unicodeEscapedString.substring(i + 2, i + 6), 16);
decodedString.appendCodePoint(codePoint);
i += 6; // 跳过这个Unicode转义序列
} else {
// 不是Unicode转义序列,直接添加字符
decodedString.append(unicodeEscapedString.charAt(i));
i++;
}
}
// 打印解码后的字符串
System.out.println(decodedString.toString());
}
3.测试
/**
* 测试
*/
@Test
public void test011() {
String str = "{\"return_code\":\"104\",\"return_msg\":\"\\u4e3a\\u5fc5\\u4f20\\u53c2\\u6570\\uff0c\\u4e0d\\u80fd\\u4e3a\\u7a7a!\"}";
unicodeEscapeToChinese (str);
}