下面是一个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来做。
发布于 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
复制相似问题