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

Blog at WordPress.com.