我有一个学生类(class),字段很少。由于某种原因,我没有获得在 Student 对象中创建的“创建的”对象。当我发送 GET 调用来接收所有学生对象的信息时,我只看到前 4 个参数。它缺少创建的字段。我错过了什么?
在 Student 构造函数中,我定义了“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"
}
最佳答案
将其添加到“默认构造函数”:
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();
}
(在声明中初始化它。)
关于java - 无法打印 REST 对象中的所有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54356963/