【发布时间】:2019-07-24 13:42:13
【问题描述】:
我的情况要求更复杂的序列化。我有一个班级Available(这是一个非常简化的sn-p):
public class Available<T> {
private T value;
private boolean available;
...
}
所以一个 POJO
class Tmp {
private Available<Integer> myInt = Available.of(123);
private Available<Integer> otherInt = Available.clean();
...
}
通常会导致
{"myInt":{available:true,value:123},"otherInt":{available:false,value:null}}
但是,我想要一个序列化程序来呈现相同的 POJO,如下所示:
{"myInt":123}
我现在拥有的:
public class AvailableSerializer extends JsonSerializer<Available<?>> {
@Override
public void serialize(Available<?> available, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
if (available != null && available.isAvailable()) {
jsonGenerator.writeObject(available.getValue());
}
// MISSING: nothing at all should be rendered here for the field
}
@Override
public Class<Available<?>> handledType() {
@SuppressWarnings({ "unchecked", "rawtypes" })
Class<Available<?>> clazz = (Class) Available.class;
return clazz;
}
}
测试
@Test
public void testSerialize() throws Exception {
SimpleModule module = new SimpleModule().addSerializer(new AvailableSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
System.out.println(objectMapper.writeValueAsString(new Tmp()));
}
输出
{"myInt":123,"otherInt"}
谁能告诉我如何做“失踪”的东西?或者如果我做错了,那我该怎么做呢?
我的限制是我不希望开发人员一直将@Json...-annotations 添加到Available 类型的字段中。所以上面的Tmp-class 是一个典型的 using 类应该是什么样子的例子。 如果可能的话......
【问题讨论】:
标签: serialization jackson