如何在Spring Rest控制器中将JSON对象请求Map到两个不同的JAVA对象

j13ufse2  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(127)

我有如下JSON请求对象:

{
    "customer" :
    {
        "id" :  100,
        "firstName": "Customer First",
        "lastName": "Customer Last"
    },

    "student" :
    {
        "id" :  "ABC-100",
        "name": "Student Name",
        "age": 20
    }

}

现在,我有一个 Spring Boot 休息控制器来读取这个请求:

@RequestMapping(value = "/save", method = RequestMethod.POST)
    public Instructor persistInstructorInformation(@RequestBody Object studentAndCustomer){
...

}

我的问题是,我们如何能够以一种不同于使用Object类的方式检索这些信息。
我并不想使用这里描述的Wrapper类:
https://stackoverflow.com/a/40275881/9728637

iklwldmw

iklwldmw1#

需要实体类:实体:

public class TheEntity {
    private Customer customer;
    private Student student;
    // getter and setter
}

public class Customer {
    private Integer id;
    private String firstName;
    private String lastName;
    // getter and setter
}

public class Student {
    private String id;
    private String name;
    private String age;
    // getter and setter
}

然后使用ThenEntity:

@RequestMapping(value = "/save", method = RequestMethod.POST)
    public Instructor persistInstructorInformation(@RequestBody TheEntity studentAndCustomer){
    System.out.println(studentAndCustomer)
    ...
}

说白了,就是根据需要封装对象

相关问题