Guice + Jersey: Custom Object Serialization

I looked at stackoverflow and the rest of the web pages for examples, but I cannot find anything that goes beyond JSON and XML serialization.

In my webapp, I want my objects to be serialized as CSV, for example.

I understand that in Jersey I can implement providers that implement the MessageBodyWriter and MessageBodyReader interfaces (or are these classes expanding?) And then force Jersey to scan the package and find and use these custom implementations. How can I do this with Guice using the JerseyServletModule function?

Is another jax-rs framework integrated with guice?

Thanks!

+4
source share
1 answer

Instead of scanning the package, you can add bindings to your implementation. MessageBodyWriter. For instance:

public class Config extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector( new JerseyServletModule() { @Override protected void configureServlets() { bind(Service.class); bind(CsvWriter.class); serve("/services/*").with(GuiceContainer.class); } }); } } 

where CsvWriter.java is as follows:

 @Singleton @Produces("text/csv") @Provider public class CsvWriter implements MessageBodyWriter<Foo> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Foo.class.isAssignableFrom(type); } @Override public long getSize(Foo data, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) { return -1; } @Override public void writeTo(Foo data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException { // Serialize CSV to out here } } 

and then enter some method in the service that @Produces ("text / csv").

+4
source

All Articles