samedi 9 mai 2015

Asymmetric serialization and deserialization using Jackson

I am using Jackson to serialize and deserialize data for a RESTful API. I'd like to have a REST resource (/comments) that allows to POST comments as well as to GET a list of comments.

Here's a (simplified) example of what gets posted to /comments.

{"text":"Text","author":"Paul","email":"paul@example.org"}

Here's what the result of GET /comments should look like:

[{"text":"Text","author":"Paul","emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]

Since email addresses shouldn't be visible to anyone, I decided to return only a MD5 hash of the email addresses in the response.

I have created a simple POJO class Comment that has fields with getters and setters for text, author, email, and emailHash.

Now, when I serialize the result, what I get is the following:

[{"text":"Text","author":"Paul","email":null,"emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]

But I really don't like email to be returned as null here. It rather shouldn't be included at all.

Using the annotation @JsonIgnore on that field will also ignore it on deserialization. Do I have to create two classes, say CreationComment and ResultComment with a super-class Comment that shares common fields or is there a way that avoids creating additional classes?

Aucun commentaire:

Enregistrer un commentaire