users@jersey.java.net

Re: [Jersey] need code samples for hooking in converters

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 16 Jun 2008 16:02:05 +0200

Mark Volkmann wrote:
> Where can I read about configuring message body readers and writers?

Please look at the links that Jakub gave you, and also look at the
example code for the EntityProvider example distributed with Jersey.


> I'm
> guessing that I need to configure a mapping between Java classes and
> their corresponding readers and writers somewhere. For example, if I'm
> working with a Java class called Car that has fields like make, model
> and year, do I need to configure the reader and writer that handles
> creating a Car object from XML and creating XML from a Car object?
>

You would need to develop code to write an instance of Car to XML and
vice versa. That code is encapsulated in MessageBodyReader and
MessageBodyWriter implementations respectively. An existing mapping that
is already implemented is that for JAXB objects to/from XML and JSON.

Skeleton code may look like this:

   @ProduceMime("application/xml")
   @ConsumeMime("application/xml")
   @Provider
   public class CarReaderWriter
       implements MessageBodyReader<Car>, MessageBodyWriter<Car> {
     public boolean isReadable(Class<?> type, Type genericType,
         Annotation annotations[]) {
       return Car.class == type;
     }

     public boolean isWriteable(Class<?> type, Type genericType,
         Annotation annotations[]) {
       return Car.class == type;
     }
     ...
   }


   @Path("/")
   @ProduceMime("application/xml")
   public class CarResource {
     @GET
     public Car getCar() {
       Car c = ...
       return c;
     }
   }

Paul.

-- 
| ? + ? = To question
----------------\
    Paul Sandoz
         x38109
+33-4-76188109