下面是一个Jersey服务:
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response service(@QueryParam("format") String format) {
if (format.equals("json")) {...}
return response;
}我希望根据XML url“格式”生成或JSON响应。
我的响应实例是由jaxb2形成的
我知道,如果在我的Java / functional上使用以下代码,我可能会得到xml或json响应:
String content = service.path("").queryParam("myparam", "myvalue").accept(MediaType.APPLICATION_XML).get(String.class);或
String content = service.path("").queryParam("myparam", "myvalue").accept(MediaType.APPLICATION_JSON).get(String.class);但我需要根据url param来做。
发布于 2013-08-03 12:13:21
可以通过Response#ok (假设您希望返回HTTP 200状态)方法直接设置响应实体的媒体类型。
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response service(@QueryParam("format") String format) {
return Response
// Set the status, entity and media type of the response.
.ok(entity, "json".equals(format) ? MediaType.APPLICATION_JSON : MediaType.APPLICATION_XML)
.build();
}或者使用Response.ResponseBuilder#header方法
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response service(@QueryParam("format") String format) {
return Response
// Set the status and Put your entity here.
.ok(entity)
// Add the Content-Type header to tell Jersey which format it should marshall the entity into.
.header(HttpHeaders.CONTENT_TYPE, "json".equals(format) ? MediaType.APPLICATION_JSON : MediaType.APPLICATION_XML)
.build();
}发布于 2014-02-13 23:23:15
这不是做你想做的事的正确方法。您不应该使用查询参数来确定输出格式。您已经声明您的资源方法同时生成了XML和JSON,标准的兼容方式是让客户端发送一个正确的HTTP“接受”报头,它声明了他们能够使用的媒体类型。如果它们发送"Accept: application/json",您的JAX实现应该选择将您的方法的响应格式化为JSON,如果客户端发送"Accept: application/ XML ",它应该自动将您的响应格式化为XML。如果客户端表示它们都可以接受,那么JAX实现可以任意选择,您不应该在意。如果客户端表示它们也不能接受,您的JAX应该发回一个适当的HTTP错误代码,表明它们没有办法返回一个正确的响应。
发布于 2016-01-31 09:43:55
这里是完整的例子,上面的答案是正确的。我也采用了上述方法,但在使用List时遇到了问题。我把实体设置成这样:
public Response getCoursesJSONOrXML(@QueryParam("type") String type){
//Here we get list
List<Course> entity= courseService.getAllCourses();
Response response = Response
.ok(entity, "xml".equals(type) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
.build();
return response;
}在那之后,我将面临这样的例外:
MessageBodyWriter not found for media type=application/json, type=class java.util.Arrays$ArrayList, genericType=class java.util.Arrays$ArrayList在阅读了泽西文档之后,我找到了我们需要在课程列表中使用GenericEntity的解决方案。这里的例子
@GET
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response getCoursesJSONOrXML(@QueryParam("type") String type){
//Here we get list
List<Course> list = courseService.getAllCourses();
GenericEntity<List<Course>> entity = new GenericEntity<List<Course>>(list) {};
Response response = Response
.ok(entity, "xml".equals(type) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON)
.build();
return response;
}https://stackoverflow.com/questions/18026296
复制相似问题