我有一门学生课,但领域很少。由于某种原因,我没有在Student对象中创建“创建的”对象。当我发送GET调用以接收所有学生对象的信息时,我仅看到前四个参数。缺少创建的字段。我想念什么?
在学生构造函数中,我定义了“ this.created = new Date();”。为创建的字段分配值。
public class Student {
private String firstName;
private String lastName;
private String address;
private String enrolledDepartment;
private Date created;
public Student() {
}
public Student(String firstName, String lastName, String address, String departmentName){
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.enrolledDepartment = departmentName;
this.created = new Date();
}
// Getter and setters of all fields
}
资源类
@Path("/students")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class StudentsResource {
List<Student> students = new ArrayList<>();
private StudentService studentService = new StudentService();
@GET
public List<Student> getProfiles() {
return studentService.getAllStudents();
}
@POST
public Student addProfile(Student profile) {
return studentService.addProfile(profile);
}
}
服务类别
public class StudentService {
private List<Student> students = DatabaseClass.getStudents();
public List<Student> getAllStudents() {
return students;
}
public Student addProfile(Student student) {
students.add(student);
return student;
}
}
数据库类
public class DatabaseClass {
private static List<Student> students = new ArrayList<>();
private static List<Email> emails = new ArrayList<>();
public static List<Student> getStudents() {
return students;
}
public static List<Email> getEmails() {
return emails;
}
}
我正在使用以下JSON发送POST请求
{
"address": "Boston",
"enrolledDepartment": "health",
"firstName": "abc",
"lastName": "pqr"
}
答案 0 :(得分:1)
将其添加到“默认构造函数”:
public Student() {
this.created = new Date();
}
...假定您未调用的构造函数,因此created
仍为null
。
甚至:
// ...
private Date created = new Date();
public Student() {
}
public Student(String firstName, String lastName, String address, String departmentName){
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.enrolledDepartment = departmentName;
//this.created = new Date();
}
(在声明中将其初始化。)