对换第三方接口,出现字符串中含有 unicode 的中文字符。百度了好久,终于找到了我自己的方案。
参考:https://blog.51cto.com/u_16175473/11119980 了这个做法,想到正则找出来转换成 utf-8 后再放回去
使用正则查找到 unicode 字符,然后转换成 utf-8 字符,再重新替换回去
/**
* 把 unicode 字符转换成 utf-8 字符。
*
* @param str
* @return
*/
public String replaceUnicode(String str) {
// 使用正则查找 unicode 编码的字符串,然后转换成字符
Pattern compile = Pattern.compile("(\\\\u\\p{XDigit}{4})");
Matcher matcher = compile.matcher(str);
while (matcher.find()) {
int i = matcher.groupCount();
for (int j = 0; j <i; j++) {
String group = matcher.group(j);
char c = (char) Integer.parseInt(group.substring(2), 16);
str = str.replace(group, String.valueOf(c));
}
}
return str;
}