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}}
There is indeed a Guava module for Jackson on GitHub, but Optional is not supported (yet). Seems like a rather straightforward serializer/deserializer to implement; the behaviour should be fairly similar to @JsonUnwrapped, so for your simple test the result should be:
{"myString":"testString"}
and for an Optional.absent the serialized form should be:
{"myString":null}
Update: Seemed simple enough so I've just implemented it and pushed it to GitHub. You can get it via the official repo and build from source, or wait for the next official release. Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With