除了 @Produces 注释之外,Jersey (JAX-RS) 如何知道将 POJO 视为特定的 mime 类型?
我看到很多 Jersey 的例子,看起来像这样:
public class ItemResource {
@GET
@Path("/items")
@Produces({"text/xml", "application/json"})
public List<Item> getItems() {
List<Item> items = new ArrayList<Item>();
Item item = new Item();
item.setItemName("My Item Name!");
items.add(item);
return items;
}
}
但是我在剖析 Item 时遇到了麻烦,以及 Jersey 如何知道如何将 Item 转换为 XML 或 JSON。我见过一些非常基本的示例,它们仅返回构造的 HTML 或 XML 的字符串,这对我来说更有意义,但我错过了下一步。我查看了这些示例,其中一个很突出(json-from-jaxb 示例),因为该对象标有这些类型的注释:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"flight"
})
@XmlRootElement(name = "flights")
我正在寻找逐步涵盖此“翻译”的教程,或此处解释如何将 POJO 转换为特定 mime 类型的输出。谢谢!
I see a lot of examples for Jersey that look something like this:
public class ItemResource {
@GET
@Path("/items")
@Produces({"text/xml", "application/json"})
public List<Item> getItems() {
List<Item> items = new ArrayList<Item>();
Item item = new Item();
item.setItemName("My Item Name!");
items.add(item);
return items;
}
}
But then I have trouble dissecting Item, and how Jersey knows how to translate an Item to either XML or JSON. I've seen very basic examples that just return a String of constructed HTML or XML, which makes more sense to me, but I'm missing the next step. I looked at the samples, and one of them stood out (the json-from-jaxb sample), since the object was marked with these types of annotations:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"flight"
})
@XmlRootElement(name = "flights")
I'm looking for tutorials that cover this "translation" step-by-step, or an explanation here of how to translate a POJO to output as a specific mime type. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有两件事在起作用。首先,@Produces 注释中的媒体类型用于内容协商。将客户端发送的 Accept 标头值中的媒体类型与 @Produces 注释中的媒体类型进行比较,并选择最合适的一种。假设您的示例中是 text/xml。
当构造响应主体时,Jersey 内部尝试找到一个可以将 Item 对象转换为 text/xml 的 MessageBodyWriter。通常程序员会提供这些“映射器”类,但对于 XML 和 JSON,为了方便起见,Jersey 已经内置了 MessageBodyReaders。
这就是为什么看起来好像发生了某种魔法。
扬
There are two things at work here. First, the media types in the @Produces annotation are used in content negotiation. The media types in the value of the Accept header sent by the client are compared to those in the @Produces annotation and the most appropriate one is selected. Suppose that is text/xml in your example.
When constructing the response body Jersey internally tries to find a MessageBodyWriter that can turn Item objects into text/xml. Usually the programmer supplies these 'mapper' classes but for XML and JSON Jersey has built in MessageBodyReaders already for convenience.
That is why it appears as if there was going on some magic.
Jan