[英]How to serialise a POJO with two different custom serialisers for two different apis in Spring MVC?
I am using Spring MVC for creating a restful API. 我正在使用Spring MVC创建一个宁静的API。 I have two different API endpoints where I need to serialise same POJO in two different ways.
我有两个不同的API端点,需要以两种不同的方式序列化相同的POJO。 I have illustrated the same below:
我已经在下面说明了相同的内容:
Course API 课程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. 我的
Course
Pojo符合上述结构,因此默认序列化有效。
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 现在,对于另一个
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: 我的
Student
班级看起来像这样:
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. 请注意,
Student
班级没有institute
财产,因为可以通过course.getInstitute
getter传递地确定course.getInstitute
。 But that ends up in a serialisation structure similar to course API. 但这最终导致了类似于课程API的序列化结构。 How can I use a custom serialisation only for the Students API without modifying the POJO Structure.
如何在不修改POJO结构的情况下仅对学生API使用自定义序列化。
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. 我想知道有N种解决方案,这是我想知道的最优雅,最喜欢的解决方案。
I guess this is the most elegant thing I sorted out which works for me. 我想这是我挑选出的最优雅的东西,对我有用。
So, here is my class Student
所以,这是我班的
Student
class Student {
private String id;
private String name;
@JsonIgnoreProperties({"institute"})
private Course course;
//getters and setters
//Adding one more getter
public Institute getInstitute() {
return this.course.getInstitute();
}
}
This way I am exposing a Java bean property institute
through a getter
while not holding a reference to it in my Student
Object. 这样,我通过
getter
公开了Java Bean属性institute
,而没有在我的Student
Object中保留对它的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.