11
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(reg_be);
oos.flush();
oos.close();

InputStream is = new ByteArrayInputStream(baos.toByteArray());

此代码将 Java转换ObjectInputStream,我如何转换InputStreamObject?我需要将我的转换ObjectInputStream然后我通过它,我想找回我Object

4

4 回答 4

16

try块中你应该写:

ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();

ObjectInputStream用另一个流初始化,例如BufferedInputStream或您的输入流is

于 2013-06-11T11:31:08.033 回答
1
ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
于 2013-06-11T11:32:51.893 回答
0

尝试以下

ObjectInputStream  ois = new ObjectInputStream(is);
Object obj = ois .readObject();
于 2013-06-11T11:34:35.787 回答
0
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;
}
于 2020-07-28T15:42:59.557 回答