假设Jackson是您的序列化器,则可以将设置
ObjectMapper为
WRAP_ROOT_VALUE。您将在
ContextResolver。为了不将相同的配置用于所有类型,可以使用两个不同的configure
ObjectMappers,一个用于list类,另一个用于其余类。例如
@Providerpublic class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { final ObjectMapper listMapper = new ObjectMapper(); final ObjectMapper defaultMapper = new ObjectMapper(); public ObjectMapperContextResolver() { listMapper.configure(SerializationFeature.INDENT_OUTPUT, true); listMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); listMapper.registerModule(new JaxbAnnotationModule()); defaultMapper.registerModule(new JaxbAnnotationModule()); } @Override public ObjectMapper getContext(Class<?> type) { if (type == MovieList.class) { return listMapper; } return defaultMapper; } }该
MessageBodyWriter用于编组会调用该
getContext方法,传递它试图元帅类。根据结果,
ObjectMapper将使用。是什么
WRAP_ROOT_VALUE呢,是在对象包住根值,名称为中值
@JsonRootName或
@XmlRootElement(JAXB给出注释支持是enabled-见这里)
测试:
@Path("/movies")public class MovieResource { @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getMovieList() { MovieList list = new MovieList(); list.add(new Movie("I Origins")); list.add(new Movie("Imitation Game")); return Response.ok(list).build(); }}C:>curl -v -H "Accept:application/json" http://localhost:8080/api/movies
结果:{ "movies" : [ { "name" : "I Origins" }, { "name" : "Imitation Game" } ]}
更新
因此,我注意到您的清单已经存在
protected。也许您稍后可能想扩展
MovieList该类。在这种情况下
if (type == MovieList.class) { return listMapper;}该机器人将是可行的。您需要检查的是类型
isAssignableFrom
if (MovieList.class.isAssignableFrom(type)) { return listMapper;}


