Java 球衣。如何根据url参数生成json和xml输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18026296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jersey. How to generate json and xml output depending on url param
提问by ses
Here is a Jersey
service:
这是一项Jersey
服务:
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response service(@QueryParam("format") String format) {
if (format.equals("json")) {...}
return response;
}
I want to generate XML
or JSON
response back depending on url param"format".
我想根据url 参数“格式”生成XML
或JSON
响应。
My responseinstance is forming by jaxb2
我的响应实例是由jaxb2
I know I may get xml
or json
response back if on my Java client / functional test by using this code:
我知道如果在我的 Java 客户端/功能测试上使用以下代码,我可能会得到xml
或json
响应:
String content = service.path("").queryParam("myparam", "myvalue").accept(MediaType.APPLICATION_XML).get(String.class);
or
或者
String content = service.path("").queryParam("myparam", "myvalue").accept(MediaType.APPLICATION_JSON).get(String.class);
But I need to do it depending on url param.
但我需要根据 url 参数来做。
采纳答案by Michal Gajdos
You can set the media type of response entity directly via Response#ok(assuming you want to return HTTP 200
status) method
可以直接通过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();
}
or by using Response.ResponseBuilder#headermethod
或使用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();
}
回答by Plínio Pantale?o
Ok. Since we are talking about things outside the pattern here let me try something:
好的。既然我们在这里谈论模式之外的事情,让我尝试一下:
How about you use a filter (look for com.sun.jersey.spi.container.ResourceFilterFactory) on your service and change (or add or overwrite) the accept header based on your query param?
您如何在您的服务上使用过滤器(查找 com.sun.jersey.spi.container.ResourceFilterFactory)并根据您的查询参数更改(或添加或覆盖)接受标头?
Not the most honest approach, I admit it, but i think you should give it a try
这不是最诚实的方法,我承认,但我认为你应该尝试一下
回答by user2456600
This is not the proper way to do what you want. You shouldn't be using a query parameter to determine output format. You have declared that your resource method produces both XML and JSON, the standard compliant way is to let the client send a proper HTTP "Accept" header which declares what media types they are able to consume. If they send in "Accept: application/json", your JAX-RS implementation should choose to format your method's response as JSON, if the client sends "Accept: application/xml", it should automatically format your response as XML. If the client indicates they can accept either, your JAX-RS implementation is free to choose either and you shouldn't care. If the client indicates they can't accept either, your JAX-RS should send back an appropriate HTTP error code indicating they don't have a way to send back a proper response.
这不是做你想做的事情的正确方法。您不应该使用查询参数来确定输出格式。您已经声明您的资源方法同时生成 XML 和 JSON,标准的兼容方式是让客户端发送一个正确的 HTTP“接受”标头,该标头声明他们能够使用哪些媒体类型。如果他们发送“Accept: application/json”,您的 JAX-RS 实现应该选择将您的方法的响应格式化为 JSON,如果客户端发送“Accept: application/xml”,它应该自动将您的响应格式化为 XML。如果客户端表明他们可以接受,那么您的 JAX-RS 实现可以自由选择,您不必在意。如果客户表示他们也不能接受,
回答by Anshu Kumar
Here the complete example, the above answer is right. I also use the above approach but facing problem while working with List. I set the entity like this:
这里是完整的例子,上面的答案是正确的。我也使用上述方法,但在使用 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;
}
After that I'm facing this exception:
之后我面临这个例外:
MessageBodyWriter not found for media type=application/json, type=class java.util.Arrays$ArrayList, genericType=class java.util.Arrays$ArrayList
After reading jersey document, I found the solution that we need to use GenericEntityfor our course list. Here the example
阅读球衣文档后,我找到了我们需要使用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;
}