【问题标题】:Process input json with illegal encoding [duplicate]使用非法编码处理输入 json [重复]
【发布时间】:2019-02-06 13:44:55
【问题描述】:

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

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

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

【问题讨论】:

  • 服务器可能会发送一个Content-Type 标头,指定编码以及数据。如果未指定编码,则 UTF-8 是 application/json 的默认值。在这种情况下,请修复服务器以发送正确编码的 Json。

标签: java json encoding character-encoding jackson


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2015-04-26
    • 2018-02-13
    • 2015-06-03
    • 2019-01-02
    • 2010-09-24
    • 1970-01-01
    相关资源
    最近更新 更多