Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to deserialize with generics using Micronaut Serialization without utilizing @SuppressWarnings("unchecked") is by using the TypeReference class provided by Jackson (Micronaut uses Jackson for its serialization and deserialization).

For example, let's say you have a JSON string that you want to deserialize into a List of Foo objects, where Foo is a generic class:

String json = "[{ \"name\": \"foo1\" },{ \"name\": \"foo2\" }]";

You can deserialize this JSON string into a List of Foos as follows:

import com.fasterxml.jackson.core.type.TypeReference;
import io.micronaut.jackson.ObjectMapper;
import javax.inject.Inject;
import java.util.List;

public class MyService {
    @Inject
    ObjectMapper objectMapper; // inject Micronaut's ObjectMapper

    public List<Foo<?>> deserialize(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<Foo<?>>>() {});
        } catch (Exception e) {
            // handle exception
        }
    }
}

In the above code, we inject Micronaut's ObjectMapper and use it to deserialize the JSON string. We pass a new instance of TypeReference<list<foo<?>>>() {} to the readValue() method to tell Jackson what type to deserialize the JSON string into. Jackson will then use the type information provided by TypeReference to properly deserialize the JSON string into a List of Foos.

Note that the TypeReference class has a generic parameter that represents the type you want to deserialize into. You can use this class to deserialize any JSON string into any generic type that you want.