我只用球衣,而不是傑克遜創造一個REST API。我有兩個示範對象,自定義對象顯示在JSON
public class Course {
private int id;
private String name;
private Teacher teacher;
}
public class Teacher {
private int id;
private String givenName;
private String familyName;
}
我創建一個服務,並返回課程對象的名單,
public List<Course> getAll(){
return db.getCourseList();
}
如預期顯示,
[{"id":101,"name":"Introduction to Java","teacher":{"familyName":"Bar","givenName":"Foo","id":201}},{"id":102,"name":"Intermediate Java","teacher":{"familyName":"Prank","givenName":"Foo","id":202}}]
現在我想要自定義我的JSON對象,以只顯示以下格式的教師ID。
[{"id":"100","name":"Introduction to Java","teacherId":"201"},{"id":"101","name":"Intermediate Java","teacherId":"201"}
所以這是我設計的視圖模型。
@XmlRootElement
public class CourseTeacherIdView {
private int id;
private String name;
private int teacherId;
CourseTeacherIdView(){
}
public CourseTeacherIdView(int id, String name, int teacherId){
this.id = id;
this.name = name;
this.teacherId = teacherId;
}
}
而且我用這個方法返回視圖對象列表。
public List<CourseTeacherIdView> getAll(){
List<Course> list = db.getCourseList();
List<CourseTeacherIdView> viewList = new ArrayList<>();
for(Iterator<Course> itr = list.iterator(); itr.hasNext();){
Course c = (Course) itr.next();
viewList.add(new CourseTeacherIdView(c.getId(), c.getName(), c.getTeacher().getId()));
}
return viewList;
}
這就是我得到的結果。
[{},{},{}]
我在做什麼錯。
其實固定它。顯然,如果這個類沒有getter和setter,這就是對象的打印方式。我添加了getters和setters,它工作正常。謝謝。 – Zeus