我正在使用Spring MVC来创建一个宁静的API。我有两个不同的API端点,我需要以两种不同的方式序列化相同的POJO。我在下面说明了相同的内容:
课程API
Course
我的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
}
Pojo符合上述结构,因此默认序列化有效。
Students
现在,另一个url - /student/{id}
response - {
"id":"s1234",
"name":"Jon Doe",
"institute": {
"id": "i1234",
"name": "XYZ college"
},
"course": {
"id": "c1234",
"name": "some-course"
}
}
API
Student
我的class Student {
private String id;
private String name;
private Course course;
//getters and setters follow
}
课程如下:
institute
请注意Student
课程中没有course.getInstitute
属性,因为学院可以通过string connectionString =
@"Data Source (LocalDB)\v11.0;AttachDbFilename='C:\Users\[UserName]\Desktop\OOPproject\Nauman(ManagementSystrm\WindowsFormsApplication1\Database1.mdf';Integrated Security=True";
getter来传递确定。但最终会出现类似于课程API的序列化结构。如何在不修改POJO结构的情况下仅为Students API使用自定义序列化。
我想到了N个解决方案,我想知道这是最优雅和最优选的解决方案。
答案 0 :(得分:0)
我想这是我整理出来的最优雅的东西,对我有用。
所以,这是我的班级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();
}
}
这样我通过institute
公开了一个Java bean属性getter
,而没有在我的Student
对象中保存对它的引用。