我正在尝试使用 Jackson 序列化 ImmutableMap<Dummy, DummyInfo> 。自定义序列化程序是专门为 Dummy 类编写的。其余的默认行为是可以的。它适用于 Dummy 类,但不适用于 ImmutableMap 对象。
序列化器类:
public class DummySerializer extends StdSerializer<Dummy> {
private final ObjectMapper mapper = new ObjectMapper();
protected DummySerializer(Class<Dummy> t) {
super(t);
}
@Override
public void serialize(Dummy dummyObj,
JsonGenerator gen,
SerializerProvider serializers)
throws IOException {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, dummyObj.getDummyId());
gen.writeFieldName(writer.toString());
}
}
用法:
ImmutableMap<Dummy, DummyInfo> map = //initialization
SimpleModule module = new SimpleModule();
module.addSerializer(new DummySerializer(Dummy.class));
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
mapper.writeValueAsString(map);
输出不是看到指定的序列化,而是 ImmutableMap 的默认字符串输出。