我有这门课
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);
请注意 ResultList
和 Product
的类类型是如何作为单独的参数传递给 constructCollectionLikeType
的。另请注意 CollectionLikeType不要求 ResultList
实现 Collection
。
最后注册SimpleModule
:
mapper.registerModule(new SimpleModule()
.addSerializer(new ListProductSerializer(type)));
关于java - Jackson Serializer 使用泛型注册 SimpleModule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45281738/