When serializing a Person
class using Jackson where Person
is:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "My name is "+name+" ("+age+")";
}
}
I get the following output:
Map<Person, String> map = new HashMap<>();
Person john = new Person("John", 20);
map.put(john, "abc");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(System.out, map); //1
objectMapper.writeValue(System.out, john); //2
1:
{"My name is John (20)":"abc"}
2:
{"name":"John","age":20}
Is there an easy way (without a custom serializer) to change the map key to use the name
attribute instead of the toString
output in #1, without losing the serialization output of the Person
object in #2, and without changing the toString
return value? I would expect there is an annotation for getName
that does this, but can't seem to find it.