You can register the serializer programatically in jackson. The class needing custom serialization:
public class SpecialObject {
private String field;
private String anotherField;
//getters, setters
}
The wrapper class, where it is a field:
public class WrapperObject {
private String text;
private SpecialObject specialObject;
//getters, setters
}
The serializer:
public class SpecialObjectSerializer extends StdSerializer<SpecialObject> {
public SpecialObjectSerializer() {
super(SpecialObject.class);
}
@Override
public void serialize(SpecialObject value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
gen.writeStringField("fieldChanged", value.getField());
gen.writeStringField("anotherFieldChanged", value.getAnotherField());
gen.writeEndObject();
}
}
Nothing fancy, just changing field names when serializing.
Now you need to add your serializer in a Module
and register that module in object mapper. You can do it like this:
public class NoAnnot {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
//add serializer in module
module.addSerializer(SpecialObject.class, new SpecialObjectSerializer());
//register module
objectMapper.registerModule(module);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
SpecialObject specialObject = new SpecialObject();
specialObject.setField("foo");
specialObject.setAnotherField("bar");
WrapperObject wrapperObject = new WrapperObject();
wrapperObject.setText("bla");
wrapperObject.setSpecialObject(specialObject);
String json = objectMapper.writeValueAsString(wrapperObject);
System.out.println(json);
}
}