John Koerner
John Koerner

Reputation: 38077

Inject a field in JSON Serialization

I am looking to inject a field into the JSON I am serializing from a POJO. I am using Jackson to perform the serialization and I can create a customer serializer to inject the field. What I have so far is:

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; }
}

Assuming that Child is a class that is part of an API and I cannot modify it. Is there a way I can modify the custom serializer to use the default serialization for the Child class, so that when Child changes, I do not have to modify the custom serializer?

Upvotes: 1

Views: 2336

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38655

You can convert object to Map add additional properties and serialize full map. See below serializer:

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;
    }
}

Upvotes: 1

Related Questions