I have a class that accept a Function<ByteBuffer, T> deserialize
as constructor argument. I want the function to convert JSON to list of objects. Here's what I am trying to do
public Function<ByteBuffer, List<MyObject>> deserialize(
final ObjectMapper objectMapper
) {
return objectMapper.readValue(??, new TypeReference<List<MyObject>>(){});
}
Obviously the syntax is wrong here. How can I fix this?
CodePudding user response:
Instead of creating such a function I would rather go with utility method because ObjectMapper.readValue()
throws IOException
which is checked. Therefore it should be handled because we can't propagate checked exceptions outside the Function
.
If you wonder how it might look like, here it is:
public Function<ByteBuffer, List<MyObject>> deserialize(ObjectMapper objectMapper) {
return buffer -> {
try {
return objectMapper.readValue(buffer.array(),new TypeReference<List<MyObject>>() {
});
} catch (IOException e) {
e.printStackTrace();
return null;
}
};
}
Instead, let's consider a utility-class:
public static final ObjectMapper objectMapper = // initializing the mapper
public static List<MyObject> deserialize(ByteBuffer buffer) throws IOException {
return objectMapper.readValue(buffer.array(),new TypeReference<>() {});
}