I am using Spring MVC for creating a restful API. I have two different API endpoints where I need to serialise same POJO in two different ways. I have illustrated the same below:
Course API
url - /course/{id}
response - {
"id": "c1234",
"name": "some-course",
"institute": {
"id": "i1234",
"name": "XYZ College"
}
}
My Course
Pojo is in accordance with the above structure, so the default serialisation works.
class Course {
private String id;
private String name;
private Institute institute;
//getters and setters follow
}
class Institute {
private String id;
private String name;
//getters and setters follow
}
Now, for another Students
API
url - /student/{id}
response - {
"id":"s1234",
"name":"Jon Doe",
"institute": {
"id": "i1234",
"name": "XYZ college"
},
"course": {
"id": "c1234",
"name": "some-course"
}
}
And my Student
class looks like this:
class Student {
private String id;
private String name;
private Course course;
//getters and setters follow
}
Please note that there is no institute
property in Student
class because institute can be transitively determined from the course.getInstitute
getter. But that ends up in a serialisation structure similar to course API. How can I use a custom serialisation only for the Students API without modifying the POJO Structure.
There are a N number of solutions to this that come to my mind, which is the most elegant and preferred one, I would like to know.