我希望将一个字段注入到我从 POJO 序列化的 JSON 中。我正在使用 Jackson 执行序列化,我可以创建一个客户序列化程序来注入该字段。到目前为止,我所拥有的是:
public class Main {
public static void main(String[] args) throws IOException {
Child newChild = new Child();
newChild.setName("John");
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("Custom Child Serializer", new Version(1,0,0,null));
module.addSerializer(new CustomChildSerializer());
mapper.registerModule(module);
System.out.println(mapper.writeValueAsString(newChild));
System.in.read();
}
}
class CustomChildSerializer extends SerializerBase<Child> {
public CustomChildSerializer() {
super(Child.class);
}
@Override
public void serialize(Child child, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonGenerationException {
jgen.writeStartObject();
jgen.writeStringField("Name", child.getName());
jgen.writeStringField("Injected Value","Value");
jgen.writeEndObject();
}
}
class Child {
private String Name;
public String getName() { return Name; }
public void setName(String name) { Name = name; }
}
假设这Child
是一个属于 API 的类,我无法修改它。有没有办法可以修改自定义序列化程序以使用Child
类的默认序列化,以便在Child
更改时不必修改自定义序列化程序?