出于通常的原因,我的CXF
提供的REST
服务通常会返回javax.ws.rs.core.Response
,以封装结果实体数据编码为 XML 和返回代码:
@GET
@Path("/getPojo")
@Produces("application/xml")
public Response getPojo() {
SomePojo resultObj = ...;
Response result = Response.status(200).entity(resultObj).build();
return result;
}
这要求 SomePojo
包含正确的注释:
@XmlRootElement(name = "somePojo")
@XmlAccessorType(XmlAccessType.FIELD)
public class SomePojo implements Serializable {
...
}
但是,现在我面临的情况是注释约定对我不起作用,我必须构建自己的 JAXBElement
。如何在 Response
中包含自定义编码(marshal)的 JAXBElement,而不是使用依赖于注释配置的 Response.ResponseBuilder.entity(resultObj)
?我正在编码类似于所解释的内容 here但他只是将编码的 XML 打印到控制台中,而我想将其打印到响应中(而不仅仅是 HttpResponse
输出)。
最佳答案
您可以使用自定义编码器编码 xml,并将结果 XML 设置为 Response
实体中的 String
或 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;
}
关于java - 如何将 JAXBElement 编码到 Response 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41622869/