Serializing POJOs With Custom Content-Type In JAX-RS 2.x 📎
public class Article {
private String name;
private String content;
public Article(String name, String content) {
this.name = name;
this.content = content;
}
@Override
public String toString() {
return "Article{" + "name=" + name + ", content=" + content + '}';
}
}
returned by a JAX-RS resource, you will need to introduce the @Produces annotation with a custom Content-type
first:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("articles")
public class ArticleResource {
@GET
@Produces("text/articles")
public Article article() {
return new Article("custom", "formats");
}
}
You get access to the POJO's instance, as well as, the server's output stream in the implementation of the MessageBodyWriter interface. Now any, also binary, format can be used to serialize the POJO passed as method parameter:
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
@Provider
@Produces("text/articles")
public class ArticleWriter implements MessageBodyWriter<Article> {
@Override
public boolean isWriteable(...) {
return true;
}
@Override
public long getSize(Article t, ...) {
return -1;
}
@Override
public void writeTo(Article t, (...), OutputStream entityStream) throws IOException, WebApplicationException {
entityStream.write(t.toString().getBytes());
}
}
[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 225 in, chapter "Binary REST Serializer "]
See you at Java EE Workshops at Munich Airport, Terminal 2, particularly at: Effective Java EE 7!