I have a value object with an Optional<Integer>
field. I want it to look like a string when it's serialized, but the Optional
part is getting in the way.
我有一个具有可选的
I have the following class:
我有以下课程:
public class Person {
private com.google.common.base.Optional<Integer> age;
public com.google.common.base.Optional<Integer> getAge() {
return age;
}
public void setAge(Integer age) {
this.age = com.google.common.base.Optional.fromNullable(age);
}
}
Here is my test:
这是我的测试:
@Test
public void testPerson() throws Exception {
ObjectMapper objectMapper = new ObjectMapper().registerModule(new GuavaModule());
Person person = new Person();
person.setAge(1);
String jsonString = objectMapper.writeValueAsString(person);
assertEquals(jsonString, "{\"age\":\"1\"}");
}
It's failing with this output:
输出是失败的:
java.lang.AssertionError: expected [{"age":"1"}] but found [{"age":1}]
. lang。AssertionError: expected [{"age":"1"}]但是找到了[{"age":1}]
I have tried adding a @JsonSerialize
annotation to the property, like this:
我尝试向属性添加一个@JsonSerialize注释,如下所示:
@JsonSerialize(using = ToStringSerializer.class)
private com.google.common.base.Optional<Integer> age;
But then the test fails like this:
但是测试失败了:
java.lang.AssertionError: expected [{"age":"1"}] but found [{"age":"Optional.of(1)"}]
. lang。AssertionError: expected [{"age":"1"}]但是找到了[{"age":"Optional.of(1)}]
I've been looking around in com.fasterxml.jackson.datatype.guava.ser.GuavaOptionalSerializer
but I can't seem to figure out how to use it correctly, if even if it's meant to be used this way.
我一直在找com.fasterxml.jackson.datatype.guava.ser。GuavaOptionalSerializer,但我似乎不知道如何正确地使用它,即使它是用这种方式使用的。
What can I do to get this test working?
我该怎么做才能让这个测试有效呢?
P.S. If it were up to me, I would remove the Optional altogether, but that's not an option.
附注:如果由我决定,我会把可选选项全部删除,但那不是一个选项。
1 个解决方案
#1
1
I ended up creating my own simple serializer:
我最终创建了自己的简单序列化器:
public class OptionalStringSerializer extends JsonSerializer<Optional<Object>> {
@Override
public void serialize(Optional<Object> value, JsonGenerator gen,
SerializerProvider serializers) throws IOException {
gen.writeString(value.isPresent() ? value.get().toString() : null);
}
}
This is how I specified it:
我是这样规定的:
@JsonSerialize(using = OptionalStringSerializer.class)
private com.google.common.base.Optional<Integer> age;
#1
1
I ended up creating my own simple serializer:
我最终创建了自己的简单序列化器:
public class OptionalStringSerializer extends JsonSerializer<Optional<Object>> {
@Override
public void serialize(Optional<Object> value, JsonGenerator gen,
SerializerProvider serializers) throws IOException {
gen.writeString(value.isPresent() ? value.get().toString() : null);
}
}
This is how I specified it:
我是这样规定的:
@JsonSerialize(using = OptionalStringSerializer.class)
private com.google.common.base.Optional<Integer> age;