Stubbisms – Tony’s Weblog

October 28, 2012

Handy Akka Java API Option Jackson Serialiser

Filed under: Java — Antony Stubbs @ 6:49 am

I know, it’s been a while.

Anyway, here’s a hand little Handy Akka Java API Option Jackson Serialiser. Easily customisable to the Scala Option version.

import akka.japi.Option;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

import java.io.IOException;

/**
 * @author Antony Stubbs 
 */
public class OptionSeraliser extends JsonSerializer<Option> {
    @Override
    public void serialize(Option value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        if (value.isEmpty())
            jgen.writeString("None");
            // jgen.writeNull();
        else
            provider.defaultSerializeValue(value.get(), jgen);
    }

}

Note, you may want to return write null instead of “None”, as could be more valid for your use case. I’m still deciding.

You then use it by annotating the field of the Option type:

    @JsonSerialize(using = OptionSerialiser.class)
    private Option<Long> secondsSinceLastEventReceived;

You could also optionally not use the type parameter on the extended class, instead passing Object into the method, and then check the type of the Object first. That way you could throw a nicer exception than a ClassCastException.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: