本文介绍了JSON:Serialize Guava可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有针对com.google.common.base.Optional的Json Serializer / Deserializer?

Is there a Json Serializer/Deserializer for com.google.common.base.Optional?

开箱即用这似乎不适用于Jackson,见下文:

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

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

推荐答案

确实存在,但是不支持Optional。看起来像一个相当简单的序列化器/解串器来实现;行为应该与@JsonUnwrapped非常相似,所以对于你的简单测试,结果应该是:

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}

{"myString":"testString"}

,对于Optional.absent,序列化表格应为:

and for an Optional.absent the serialized form should be:

{myString:null}

{"myString":null}

更新:看起来很简单所以我刚刚实现了它并将其推送到GitHub。您可以通过官方仓库获取并从源代码构建,或等待下一个正式版本。享受!

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!

这篇关于JSON:Serialize Guava可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:59