首页 > 解决方案 > 处理非法编码的输入 json

问题描述

我的 java 应用程序有消费者从服务器获取输入 JSON 文件,然后我尝试使用 Jackson 转换它。但是 ObjectMapper 抛出异常:

com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x2f

据我了解,这是由于编码不正确。我可以以某种方式识别编码并处理服务器响应吗?

标签: javajsonencodingcharacter-encodingjackson

解决方案


我需要识别编码并正确处理数据。为此,我使用了 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();
}

推荐阅读