简体   繁体   中英

How to marshal JAXBElement into Response?

My CXF provided REST services usually return javax.ws.rs.core.Response for the usual reason, to encapsulate the result entity data marshaled as XML and a return code:

@GET
@Path("/getPojo")
@Produces("application/xml")
public Response getPojo() {

    SomePojo resultObj = ...;

    Response result = Response.status(200).entity(resultObj).build();

    return result;
}

which requires that SomePojo contains proper annotations:

@XmlRootElement(name = "somePojo")
@XmlAccessorType(XmlAccessType.FIELD)
public class SomePojo implements Serializable {
    ...
}

However, now I am facing a scenario where the annotation convention does not work for me and I have to build my own JAXBElement . How can I include the custom-marshaled JAXBElement in the Response instead of using Response.ResponseBuilder.entity(resultObj) , which relies on the annotation configuration? I am marshaling something similar to what is explained here but he's just printing the marshaled XML into the console and I would like to print it into the Response (and not just HttpResponse out).

You can marshall the xml using your custom marshaller and set the resultant XML in the entity of the Response , as String or InputStream

@GET
@Path("/getXML")
@Produces("application/xml")
public Response getXML() {

    String xml = // custom marshall

    Response result = Response.
           status(200).
           entity(xml).
           type("application/xml").
           build();

    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM