ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(reg_be);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
此代码将Java Object
转换为InputStream
,如何将InputStream
转换为Object
?我需要将Object
转换为InputStream
然后我将其传递给我,我想让我的Object
回来。
答案 0 :(得分:15)
在try
区块中你应该写:
ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
ObjectInputStream
初始化为另一个流,例如BufferedInputStream
或您的输入流is
。
答案 1 :(得分:2)
ObjectInputStream ois = new ObjectInputStream(is);
Object o - ois.readObject();
答案 2 :(得分:0)
尝试以下
ObjectInputStream ois = new ObjectInputStream(is);
Object obj = ois .readObject();
答案 3 :(得分:0)
ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
如@darijan所述,工作正常。 但是,我们再次需要尝试捕获该代码的块,对于空白输入流,它将给出EOF(文件末尾)相关的错误。
因此,我将其转换为字符串。然后,如果字符串不为空或为null,则只有我使用ObjectMapper将其转换为Object
虽然这不是一种有效的方法,但我不必担心try-catch的问题,空处理也可以在字符串中完成,而不是在输入流中完成
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;
}