除了@Produces批注之外,Jersey(JAX-RS)如何知道将POJO视为特定的mime类型? [英] Beyond the @Produces annotation, how does Jersey (JAX-RS) know to treat a POJO as a specific mime type?

查看:112
本文介绍了除了@Produces批注之外,Jersey(JAX-RS)如何知道将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;
    }
}

但是,我在剖析Item时遇到了麻烦,Jersey如何知道如何将Item转换为XML或JSON.我已经看到了非常基本的示例,这些示例仅返回构造的HTML或XML的字符串,这对我来说更有意义,但是我错过了下一步.我查看了样本,其中一个样本脱颖而出(即json-from-jaxb样本),因为该对象已使用以下类型的注释进行了标记:

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")

我正在寻找逐步解决此翻译"问题的教程,或者在此说明如何将POJO转换为特定的mime类型输出.谢谢!

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!

推荐答案

这里有两件事在起作用.首先,@ Produces批注中的媒体类型用于内容协商.将客户端发送的Accept标头的值中的媒体类型与@Produces批注中的媒体类型进行比较,并选择最合适的媒体类型.假设您的示例中为text/xml.

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.

构造响应正文时,Jersey在内部尝试找到一个MessageBodyWriter,它可以将Item对象转换为text/xml.通常,程序员会提供这些映射器"类,但是对于XML和JSON Jersey,为了方便起见,它们已经内置了MessageBodyReaders.

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

这篇关于除了@Produces批注之外,Jersey(JAX-RS)如何知道将POJO视为特定的mime类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆