java - Jackson Serializer 使用泛型注册 SimpleModule

标签 java json serialization jackson add

我有这门课

public class ResultList<T> {......}

和我的JsonSerializer

public class ListProductSerializer extends JsonSerializer<ResultList<Product>> {..}

如何在ObjectMapper中注册SimpleModule

这不行

MAPPER.registerModule(new SimpleModule()
                .addSerializer(ResultList.class, new ListProductSerializer()));

我收到这个错误

Error:(67, 17) java: method addSerializer in class com.fasterxml.jackson.databind.module.SimpleModule cannot be applied to given types;
  required: java.lang.Class<? extends T>,com.fasterxml.jackson.databind.JsonSerializer<T>
  found: java.lang.Class<com.onkalo.rest.json.wrapper.ResultList>,com.onkalo.rest.json.serializer.ListProductSerializer
  reason: cannot infer type-variable(s) T
    (argument mismatch; java.lang.Class<com.onkalo.rest.json.wrapper.ResultList> cannot be converted to java.lang.Class<? extends com.onkalo.rest.json.wrapper.ResultList<com.onkalo.service.domain.Product>>)

最佳答案

解决这个问题的方法是使用 StdSerializer而不是它的基类 JsonSerializer,使用您当前使用的相同 serialize 方法和一个采用 JavaType 的构造函数例如:

class ListProductSerializer extends StdSerializer<ResultList<Product>> {
    ListProductSerializer(JavaType type) {
        super(type);
    }

    @Override
    public void serialize( // your serialize method
}

在您的情况下,这将是一个合适的 JavaType:

CollectionLikeType type = MAPPER.getTypeFactory()
        .constructCollectionLikeType(ResultList.class, Product.class);

请注意 ResultListProduct 的类类型是如何作为单独的参数传递给 constructCollectionLikeType 的。另请注意 CollectionLikeType不要求 ResultList 实现 Collection

最后注册SimpleModule:

mapper.registerModule(new SimpleModule()
        .addSerializer(new ListProductSerializer(type)));

关于java - Jackson Serializer 使用泛型注册 SimpleModule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45281738/

相关文章:

java - SpringBoot/spring-kafka 应用程序中的 Autowiring KafkaTemplate 抛出空指针

json - Go:检测无效 JSON 字符串字符的最佳方法是什么?

c# - 使用 DataContract Serializer 进行序列化

php - 根据 ID 将序列化的 JS 数组分组为相似的对象/数组

c++ - 升级 Boost Serialization 与二进制归档 armv7 到 arm64 的兼容性

java - 解决一个java谜语

java - 如何将 Jasypt 与 Spring Autowiring 一起使用?

java - 与Java编程的混淆

json - jq 流 - 过滤嵌套列表并保留全局结构

python - 打印所有端口值