问题
I have a class:
public class Item {
private String firstName;
private String lastName;
private int age;
}
When I convert it to JSON, I would like to combine the firstName and lastName fields. So something like:
ObjectMapper objMapper = createMapper();
Item item = new Item("Bob", "Smith", 190);
String json = objMapper.writeValueAsString(item);
But I would like the json to look as follows:
{
"Name": "Bob Smith",
"age" : "190"
}
instead of:
{
"firstName": "Bob",
"lastName" : "Smith",
"age" : "190"
}
Like wise, I would like to go the other way around. So if String anotherString is,
{
"Name": "Jon Guy",
"age" : "20"
}
objMapper.readValue(anotherString, Item);
should produce an Item with firstname = Jon, lastName = Guy, age = 20
In summary during Serialization: firstName and lastName are removed, Name is added. During Deserialization: Name is removed, firstName and lastName are restored to the object.
I've heard some solutions where we annotate the Item class. However, I would like to avoid doing this. Instead, I would like all of the code to be added via a custom serializer/deserializer.
来源:https://stackoverflow.com/questions/38231692/custom-serializer-and-deserializer-to-concatenate-two-fields-during-serializatio