konstantin
konstantin

Reputation: 725

Guice + Jersey: custom serialization of entities

I browsed the stackoverflow and the rest of the web for examples, but I can't find any that go beyond JSON and XML serialization.

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

I understand in Jersey I can implement Providers that implement MessageBodyWriter and MessageBodyReader interfaces (or are these classes to extend? whatever) and then make Jersey to scan a package and find and use these custom implementations. How do I do that with Guice, using the JerseyServletModule?

Is another jax-rs framework integrated with guice nicely?

Thanks!

Upvotes: 4

Views: 1833

Answers (1)

condit
condit

Reputation: 10962

Instead of scanning the package you should be able to add bindings to your implementation of MessageBodyWriter. For example:

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 looks like:

@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 have some method in Service that @Produces("text/csv").

Upvotes: 4

Related Questions