Custom serializer and deserializer to concatenate two fields during serialization/deserialization Jackson

偶尔善良 提交于 2019-12-24 09:29:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!