java \\u \u 转换

来源:互联网 发布:凤凰金融 以大数据 编辑:程序博客网 时间:2024/04/30 00:10

最近研究短信轰炸的时候遇到一个问题, 有些接口写的乱七八糟

返回值竟然把  汉字utf-8格式\uxxxx之类的 \u转义成 \\u

String source = "{\"status\": \"error\", \"msg\": \"\u4eca\u5929\u9a8c\u8bc1....";System.out.println(source);System.out.println(URLDecoder.decode(source, "utf-8"));source = "{\"status\": \"error\", \"msg\": \"\\u4eca\\u5929\\u9a8c\\u8bc1....";System.out.println(URLDecoder.decode(source, "utf-8"));
运行结果

{"status": "error", "msg": "今天验证....{"status": "error", "msg": "今天验证....{"status": "error", "msg": "\u4eca\u5929\u9a8c\u8bc1....

遇到这种情况 ,需要把\\uxxxx转换为\uxxxx

if (source.contains("\\u")) {StringBuffer buf = new StringBuffer();Matcher m = Pattern.compile("\\\\u([0-9A-Fa-f]{4})").matcher(source);while (m.find()) {try {int cp = Integer.parseInt(m.group(1), 16);m.appendReplacement(buf, "");buf.appendCodePoint(cp);} catch (NumberFormatException e) {}}m.appendTail(buf);String result = buf.toString();System.out.println(result);}

参考资料

http://stackoverflow.com/questions/10035891/how-to-replace-u-by-u-in-java-string

0 0
原创粉丝点击