user1827257 user1827257 - 4 months ago 12
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) {
this.name = name;
this.surname = surname;
}

public String getName() {
return name;
}

public String getSurname() {
return surname;
}
}


and MixIn class like this:

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


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

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

Answer

You could write a custom serializer:

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

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());
mapper.registerModule(module);

System.out.println(mapper.writeValueAsString(new Person("user", "1827257")));