REST API with JSON representations using Apache CX

2019-05-25 01:20发布

问题:

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(); 
}

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.

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.

回答1:

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.