JSON Serialization of Guava Optional

743 views
Skip to first unread message

Simone Hinterseher

unread,
May 23, 2012, 12:11:29 PM5/23/12
to mongo-jackson-mapper
Is there a Json Serializer/Deserializer for
com.google.common.base.Optional?

Out of the box this doesn't seem to work with Jackson, see below:

package com.example;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.google.common.base.Optional;

public class TestClass {

public Optional<String> myString;

public TestClass() {
myString = Optional.of("testString");
}

public static void main(String[] args) throws JsonGenerationException,
JsonMappingException, IOException {
TestClass testClass = new TestClass();
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(testClass);
System.out.println(jsonString);
}
}

-> {"myString":{"present":true}}

James Roper

unread,
May 30, 2012, 5:25:14 AM5/30/12
to mongo-jack...@googlegroups.com
Hi Simone,

No, Jackson does not come in with built in serialisers for Guava classes.  However, it shouldn't be hard to write one, off the top of my head, it would look roughly like this (note, I've never used the Guava optional interface, so I'm guessing what it looks like):

public class OptionalSerializer extends JsonSerializer<Optional<String>> {
  public void serialize(JsonGenerator jgen, Optional<String> option) {
     if (option.isDefined()) {
       jgen.writeString(option.getValue());
     } else {
       jgen.writeNull();
     }
   }
}

If you wanted to generically handle all types of Optional, it would get a little more complex, but not impossible.  You can then register this serialiser with an ObjectMapper, and then pass that object mapper to the JacksonDBCollection.wrap() method (don't forget to call MongoJacksonModule.configure(objectMapper) first!).

Cheers,

James
Reply all
Reply to author
Forward
0 new messages