使用不带Spring的Apache CXF的带有JSON表示形式的REST API [英] REST API with JSON representations using Apache CXF without Spring

查看:158
本文介绍了使用不带Spring的Apache CXF的带有JSON表示形式的REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的REST API中同时支持资源的XML和JSON表示形式.我别无选择,只能在不使用Spring的情况下使用Jax-RS的CXF实现.我正在使用JAXB来编组和解组对象.我定义了以下方法,它们返回同一资源的不同表示形式.

I want to support both XML and JSON representations of Resources in my REST API. I have no choice but to use CXF implementation of Jax-RS without using Spring. I am using JAXB to marshall and unmarshall objects. I have the following methods defined that return different representations of the same resource.

@GET
@Produces({MediaType.APPLICATION_XML, MediaType.WILDCARD})
@ElementClass(response = MyList.class)
public Response listXML(){
    MyList list = getList();
    return Response.status(
    Response.Status.FOUND).
    entity(list).type(MediaType.APPLICATION_XML).build();
}



@GET
@Produces({MediaType.APPLICATION_JSON})
@ElementClass(response = MyList.class)
public Response listJson(){
    MyList list = getList();
    return Response.status(
    Response.Status.FOUND).
    entity(list).type(MediaType.APPLICATION_JSON).build(); 
}

这对于XML表示来说很好用.但是,如果我将HTTP请求的Accept标头设置为application/json,则会收到以下消息.

This works fine for the XML representation. But if I set the Accept header of my HTTP request to application/json I get the following message.

No message body writer has been found for response class MyList.

我在这里想念什么? MyList类由JAXB从XSD生成,并具有所有必要的批注看起来我需要配置CXF以使用JSON提供程序.我无法在不使用Spring的Web应用程序的web.xml中找到有关配置JSON提供程序的良好文档.如果有人做过这项工作,请指导我.

What am I missing here? The MyList class is generated by JAXB from XSDs and has all the necessary annotations Looks like I need to configure CXF to use a JSON provider. I haven't been able to find good documentation on configuring the JSON provider in the web.xml for a webapplication that doesn't use Spring. If anyone has got this work, please guide me.

推荐答案

我明白了.我需要在部署描述符中将JSONProvider配置为NonSpringServlet的initparams之一.在我错过cxf扩展库和jettison库之前,这对我不起作用.如果您仅依赖于cxf前端jar,这些依赖就不会被maven或gradle自动提取.

I got it figured out. I needed to configure JSONProvider as one of initparams for NonSpringServlet in the deployment descriptor. This wasn't working for me before as I was missng the cxf extensions library and the jettison library. These dependencies don't get automatically pulled by maven or gradle if you only have a dependency on cxf front end jars.

这篇关于使用不带Spring的Apache CXF的带有JSON表示形式的REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆