5 回答

TA贡献1786条经验 获得超11个赞
String str = "\u8eab\u4efd\u8bc1\u53f7\u7801\u4e0d\u5408\u6cd5!";
byte[] bt = str.getBytes("utf-8");
String ret = new String(bt, "utf-8");
System.out.println(ret);
输出:身份证号码不合法!

TA贡献1820条经验 获得超10个赞
建议用ali的fastjson会默认转换unicode为utf-8
@Test
public void testparse(){
String jsonResult="{\"errNum\":-1,\"retMsg\":\"\u8eab\u4efd\u8bc1\u53f7\u7801\u4e0d\u5408\u6cd5!\",\"retData\":[]}";
JSONObject jsonObject=JSONObject.parseObject(jsonResult);
System.out.println(jsonObject.toJSONString());
}
输出:{"errNum":-1,"retMsg":"身份证号码不合法!","retData":[]}

TA贡献2011条经验 获得超2个赞
Gson会把html标签,转换为Unicode转义字符
正确方法:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();

TA贡献1840条经验 获得超5个赞
我也遇到过,还是URLDecoder.decode()、和其他办法,可是不管用。也不知道是哪里出问题,也许是开始不应该把 jsonResult 当成字符串吧。
最后自己写了个方法来转换字符串。
/**
* http 请求数据返回 json 中中文字符为 unicode 编码转汉字转码
* @param theString
* @return
*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
outBuffer.append(aChar);
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
添加回答
举报