JSON: Serialize Guava Optional

ぃ、小莉子 提交于 2020-01-01 12:31:09

问题


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


回答1:


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!




回答2:


There is a library with Guava Jackson serializers/deserializers here. However there is no one for optional. But it is a really basic class, and you can write one yourself easily following the samples there. Then you can pass the code to Tatu so he can add it to the library and that would be appreciated.




回答3:


I have the same the problem and i resolved my problem by using a JsonSerializer and a JsonDeserializer as the How to serialize / deserialize a Option<> class (functional java) with JSON?. Hope this helps.



来源:https://stackoverflow.com/questions/10723826/json-serialize-guava-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!