ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
正如@darijan 所说,工作正常。但是我们需要再次尝试,捕获该代码的块,并且对于空白输入流,它将给出与 EOF(文件结尾)相关的错误。
因此,我将其转换为字符串。然后,如果字符串不为空或 null,那么只有我使用 ObjectMapper 将其转换为 Object
虽然它不是一种有效的方法,但我不需要担心 try-catch,null 处理也是在字符串而不是输入流中完成的
String responseStr = IOUtils.toString(is, StandardCharsets.UTF_8.name());
Object object = null;
// is not null or whitespace consisted string
if (StringUtils.isNotBlank(response)) {
object = getJsonFromString(response);
}
// below codes are already used in project (Util classes)
private Object getJsonFromString(String jsonStr) {
if (StringUtils.isEmpty(jsonStr)) {
return new LinkedHashMap<>();
}
ObjectMapper objectMapper = getObjectMapper();
Map<Object, Object> obj = null;
try {
obj = objectMapper.readValue(jsonStr, new TypeReference<Map<Object, Object>>() {
});
} catch (IOException e) {
LOGGER.error("Unable to parse JSON : {}",e)
}
return obj;
}
private ObjectMapper getObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
return objectMapper;
}