查看Unicode和中文互转工具:
获取响应内容如下:
{"code":10000,"msg":"\u6210\u529f"}
Unicode转换为中文字符
新建解码方法:
/**
* 将Unicode编码转换为中文字符串
* @param str Unicode编码
* @return
*/
public static String unicodeToCN(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
在响应/打印前调用unicodeToCN方法
public static void main(String[] args) {
/** \u6210\u529f ==> 成功 */
String toCN = unicodeToCN("\\u6210\\u529f");
System.out.println(toCN); // 成功
}
中文字符转换为Unicode
/**
* 中文转Unicode编码
* @param string 中文内容
* @return
*/
public static String cnToUnicode(String string) {
char[] utfBytes = string.toCharArray();
String unicodeBytes = "";
for (int i = 0; i < utfBytes.length; i++) {
String hexB = Integer.toHexString(utfBytes[i]);
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB;
}
return unicodeBytes;
}
调用cnToUnicode方法
public static void main(String[] args) {
/** 成功 ==> \u6210\u529f */
String toUnicode = cnToUnicode("成功");
System.out.println(toUnicode);
}
完整代码:
package demo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
/**
* 将Unicode编码转换为中文字符串
* @param str Unicode编码
* @return
*/
public static String unicodeToCN(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
/**
* 中文转Unicode编码
* @param string 中文内容
* @return
*/
public static String cnToUnicode(String string) {
char[] utfBytes = string.toCharArray();
String unicodeBytes = "";
for (int i = 0; i < utfBytes.length; i++) {
String hexB = Integer.toHexString(utfBytes[i]);
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB;
}
return unicodeBytes;
}
public static void main(String[] args) {
/** \u6210\u529f ==> 成功 */
String toCN = unicodeToCN("\\u6210\\u529f");
System.out.println(toCN); // 成功
/** 成功 ==> \u6210\u529f */
String toUnicode = cnToUnicode("成功");
System.out.println(toUnicode);
}
}