java - 处理非法编码的输入 json
问题描述
我的 java 应用程序有消费者从服务器获取输入 JSON 文件,然后我尝试使用 Jackson 转换它。但是 ObjectMapper 抛出异常:
com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x2f
据我了解,这是由于编码不正确。我可以以某种方式识别编码并处理服务器响应吗?
解决方案
我需要识别编码并正确处理数据。为此,我使用了 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();
}
推荐阅读
- java - android 使用语句
- php - 插入具有更高顺序值的新行时,如何更改表中的顺序值?
- android - 使用 ViewModel 模式 RoomDatabase 从 DAO 获取一次数据
- azure - 列出 Azure Active Directory 用户的订阅
- amazon-s3 - 上传到 s3 时出错`options request denied upload`
- excel - 为什么 OLE 对象退出后 Excel 进程保持打开状态?
- node.js - 当表中的某些对象没有特定的搜索 ID 时,如何使用 mongoose 更新对象
- spring - 使用 Postgresql 使用 Spring Data R2DBC 保存对象时如何检索生成的 ID
- android - 如何使用 Retrofit 在 recyclerView 中正确加载更多项目?(科特林)
- c++ - 如何将 C++ 引用和指针返回转换为 C++/CLR