views:

225

answers:

1

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!

+3  A: 

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

Jan Algermissen