java解析十六进制编码字符串

在使用hbase shell等命令时,若输出的内容包含中文,经常会出现乱码等现象,我们可以在命令后面加上 {formatter => 'tostring'}来处理 例如:

scan 'test', {formatter => 'tostring'}那么,在java中如何来解析这些字符串,使之能正常显示中文呢?可以参考下面的代码:

带解析字符串为:

{
	"first_name":"\xE4\xB8\x89\xE5\x8F\xB6\xE4\xB8\x9C\xE8\xB7\xAF",
	"second_name":"\xE4\xB8\x89\xE5\x8F\xB6\xE4\xB8\x9C\xE8\xB7\xAF"
}

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {
    private static final Pattern UNICODE_PATTERN = Pattern.compile("\\\\x([0-9a-fA-F]{2})");

    public static String decodeJson(String json) {
        Matcher matcher = UNICODE_PATTERN.matcher(json);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            char c = (char) Integer.parseInt(matcher.group(1), 16);
            matcher.appendReplacement(sb, String.valueOf(c));
        }
        matcher.appendTail(sb);
        return new String(sb.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String json = "{\"first_name\":\"\\xE4\\xB8\\x89\\xE5\\x8F\\xB6\\xE4\\xB8\\x9C\\xE8\\xB7\\xAF\",\"second_name\":\"\\xE4\\xB8\\x89\\xE5\\x8F\\xB6\\xE4\\xB8\\x9C\\xE8\\xB7\\xAF\"}";
        String decodedStr = decodeJson(json);
        System.out.println(decodedStr);  // 输出解码后的字符串
    }
}

输出结果为:

{
  "first_name": "三叶东路",
  "second_name": "三叶东路"
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值