Home > Back-end >  Applying java.util.function.Function to JSON Deserialization
Applying java.util.function.Function to JSON Deserialization

Time:09-09

I have a class that accept a function Function<ByteBuffer, T> deserialize as a constructor argument.

I want to create a function which converts JSON into a 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<>() {});
}
  • Related