Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON: Serialize Guava Optional

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}}

like image 597
Hansi Avatar asked Dec 06 '22 14:12

Hansi


1 Answers

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!

like image 145
Pascal Gélinas Avatar answered Dec 09 '22 03:12

Pascal Gélinas