Reputation: 177
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(reg_be);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
This code convert Java Object
to InputStream
and how can I convert InputStream
to an Object
? I need to convert my Object
to an InputStream
then I pass it and I want to get my Object
back.
Upvotes: 11
Views: 52697
Reputation: 89189
ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
Upvotes: 1
Reputation: 4414
ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
As mentioned by @darijan is working fine. But again we need to do try, catch block for that code, & for blank input stream it will give EOF (End Of File) related error.
So, I am converting it to a string. Then if the string is not empty or null, then only I am converting it to Object using ObjectMapper
Although it's not an efficient approach, I don't need to worry about try-catch, null handling also is done in a string instead of the input stream
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;
}
Upvotes: 0
Reputation: 9795
In try
block you should write:
ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
ObjectInputStream
is initialized with another stream, e.g. BufferedInputStream
or your input stream is
.
Upvotes: 18
Reputation: 69025
Try the following
ObjectInputStream ois = new ObjectInputStream(is);
Object obj = ois .readObject();
Upvotes: 0