栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

强制JAX-RS将我的类序列化为JSON对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

强制JAX-RS将我的类序列化为JSON对象

假设Jackson是您的序列化器,则可以将设置

ObjectMapper
WRAP_ROOT_VALUE
。您将在
ContextResolver
。为了不将相同的配置用于所有类型,可以使用两个不同的configure
ObjectMapper
s,一个用于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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636773.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号