I have a spring boot service and API. The API response has a field called as information whose json field name is to be modified as per type of the response.
e.g
{
id: "",
event_details: {
"name": "abc",
"type": "a"
},
a_information: {
}
}
Currently there are only 2 types – a and b, but in future there can be more.
For b, the information field would become b_information.
As of now, I have solved this problem using custom serializer, which checks for responseObject.eventDetails.type object and writes field name accordingly.
However this looks little difficult to maintain. Is there any better way to take care of this, that I might have missed?
2
It’s better to generalize JSON structure a little:
{
“id”: “”,
“type”: “a”,
“name”: “abc”,
“payload”: {}
}
For each event you will have your own class, designed in a way that Jackson can serialize it (getters, annotations, etc.). After which your method will be able to return various events, and Jackson will serialize them into JSON (you can specify the return type of Object
or some generalized event for the method).