开发者

Beyond the @Produces annotation, how does Jersey (JAX-RS) know to treat a POJO as a specific mime type?

开发者 https://www.devze.com 2022-12-28 13:38 出处:网络
I see a lot of examples for Jersey that look something like this: public class ItemResource { @GET 开发者_如何学JAVA@Path(\"/items\")

I see a lot of examples for Jersey that look something like this:

public class ItemResource {

    @GET
    开发者_如何学JAVA@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!


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

0

精彩评论

暂无评论...
验证码 换一张
取 消