Serializing POJOs With Custom Content-Type In JAX-RS 2.x

To serialize a POJO:


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!


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Why do you need that? Which is the specific requirement/use case for wanting a custom content type? Not arguing, just a genuine question! :)

Posted by Simone P. on November 14, 2016 at 03:47 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License