我有这个班级
JsonSerializer
和我的public class ListProductSerializer extends JsonSerializer<ResultList<Product>> {..}
班级
ObjectMapper
如何在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>>)
我收到此错误
{{1}}
答案 0 :(得分:4)
解决此问题的方法是使用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)));