我正在使用基于@JsonView
的序列化模型。我通常用这样的ContextResolver
配置jackson:
@Override
public ObjectMapper getContext(Class<?> aClass) {
// enable a view by default, else Views are not processed
Class view = Object.class;
if (aClass.getPackage().getName().startsWith("my.company.entity")) {
view = getViewNameForClass(aClass);
}
objectMapper.setSerializationConfig(
objectMapper.getSerializationConfig().withView(view));
return objectMapper;
}
如果我序列化单个实体,这可以正常工作。但是,对于某些用例,我想使用与单个实体相同的视图序列化我的实体列表。在这种情况下,aClass
为ArrayList
,因此通常的逻辑没有多大帮助。
所以我正在寻找一种方法来告诉杰克逊使用哪种观点。理想情况下,我写道:
@GET @Produces("application/json; charset=UTF-8")
@JsonView(JSONEntity.class)
public List<T> getAll(@Context UriInfo uriInfo) {
return getAll(uriInfo.getQueryParameters());
}
并在JSONEntity
视图下序列化。 RestEasy有可能吗?如果没有,我该如何模仿呢?
编辑:我知道我可以自己进行序列化:
public String getAll(@Context UriInfo info, @Context Providers factory) {
List<T> entities = getAll(info.getQueryParameters());
ObjectMapper mapper = factory.getContextResolver(
ObjectMapper.class, MediaType.APPLICATION
).getContext(entityClass);
return mapper.writeValueAsString(entities);
}
然而,这最多是笨拙的,并且打败了框架处理这个样板的整个想法。
答案 0 :(得分:5)
事实证明, 可以简单地使用@JsonView
注释特定端点(就像在我的问题中一样)并且jackson将使用此视图。谁会想到。
您甚至可以通用方式(more context in my other question)执行此操作,但这与RestEasy有关:
@Override
public void writeTo(Object value, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHd,
OutputStream out) throws IOException {
Class view = getViewFromType(type, genericType);
ObjectMapper mapper = locateMapper(type, mediaType);
Annotation[] myAnn = Arrays.copyOf(annotations, annotations.length + 1);
myAnn[annotations.length] = new JsonViewQualifier(view);
super.writeTo(value, type, genericType, myAnn, mediaType, httpHd, out);
}
private Class getViewFromType(Class<?> type, Type genericType) {
// unwrap collections
Class target = org.jboss.resteasy.util.Types.getCollectionBaseType(
type, genericType);
target = target != null ? target : type;
try {
// use my mix-in as view class
return Class.forName("example.jackson.JSON" + target.getSimpleName());
} catch (ClassNotFoundException e) {
LOGGER.info("No view found for {}", target.getSimpleName());
}
return Object.class;
}