user1827257 user1827257 - 1 year ago 75
Java Question

JAVA object mapper serialization with mixin and changed getter

I'm mapping object (code to which I have no access) into json using Jackson Object Mapper and MixIn class. So, for example i have this object:

public class Person {
private String name;
private String surname;

public Person (String name, String surname) { = name;
this.surname = surname;

public String getName() {
return name;

public String getSurname() {
return surname;

and MixIn class like this:

abstract class MixIn {
abstract String getSurname(); // we don't need this in json output!

This working well. But what if i need to change output of
getter to return like
return + " " + person.surname

Is this even possible to do by specific Object Mapper configuration? (when i have no access to Person class code)

Answer Source

You could write a custom serializer:

class PersonSerializer extends JsonSerializer<Person> {
    public void serialize(Person person, JsonGenerator generator, SerializerProvider provider) throws IOException {
        generator.writeStringField("name", person.getName() + " " + person.getSurname());

Then, there are multiple ways to register it, for example using a module:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Person.class, new PersonSerializer());

System.out.println(mapper.writeValueAsString(new Person("user", "1827257")));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download