java - 无法打印 REST 对象中的所有参数

标签 java rest api

我有一个学生类(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/

相关文章:

python - 使用sightengine api 时,“检查​​”对象没有属性 'image'

php - 如何使用 instagram api 获取带有特定标签的图像?

java - 为什么 SAP JCo 会引发错误 "Field ... not a member of ...",即使该字段存在?

Java无法识别已定义的变量?

java - 比较对列表以找到相似项

rest - 如何在flask-reSTLess中打补丁?

Python Twitter 工具 - 将多个用户添加到列表失败 (lists.members.create_all)

java - Android 数据库应用程序在模拟器上运行良好,但在设备上出现错误

php - 使用现有的 Laravel Controller 编写 Web 服务

c# - 如何在 Azure 中列出经典虚拟机