为了账号安全,请及时绑定邮箱和手机立即绑定

使用非法编码处理输入 json

使用非法编码处理输入 json

幕布斯6054654 2022-06-08 17:03:19
我的 java 应用程序有消费者从服务器获取输入 JSON 文件,然后我尝试使用 Jackson 转换它。但是 ObjectMapper 抛出异常:com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x2f据我了解,这是由于编码不正确。我可以以某种方式识别编码并处理服务器响应吗?
查看完整描述

1 回答

?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

我需要识别编码并正确处理数据。为此,我使用了 UniversalDetectororg.mozilla.universalchardet.UniversalDetector


private static final UniversalDetector DETECTOR = new UniversalDetector(null);


private static String getEncode(byte[] data) throws IOException {

    DETECTOR.reset();


    byte[] buf = new byte[data.length];

    InputStream is = new ByteArrayInputStream(data);


    int read;

    while ((read = is.read(buf)) > 0 && !DETECTOR.isDone()) {

        DETECTOR.handleData(buf, 0, read);

    }

    is.close();


    DETECTOR.dataEnd();

    return DETECTOR.getDetectedCharset();

}

然后我用正确的编码阅读它:


private static String readWithEncode(byte[] data, String encoding) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data), encoding));

    StringBuilder result = new StringBuilder();

    String s;

    while ((s = br.readLine()) != null) {

        result.append(s);

    }

    br.close();

    return result.toString();

}


查看完整回答
反对 回复 2022-06-08
  • 1 回答
  • 0 关注
  • 100 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号