1

我希望将一个字段注入到我从 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更改时不必修改自定义序列化程序?

4

1 回答 1

1

您可以转换对象以Map添加其他属性并序列化完整地图。请参见下面的序列化程序:

class CustomChildSerializer extends JsonSerializer<Child> {

    ObjectMapper mapper = new ObjectMapper();
    MapType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, String.class);

    @Override
    public void serialize(Child child, JsonGenerator jgen, SerializerProvider serializerProvider)
            throws IOException, JsonGenerationException {
        Map<String, String> map = mapper.convertValue(child, type);
        map.put("Injected Value", "Value");

        jgen.writeObject(map);
    }

    @Override
    public Class<Child> handledType() {
        return Child.class;
    }
}
于 2013-10-18T00:15:15.533 回答