Spring REST API 正在响应中添加额外的键值对

Spring REST API is adding extra key-value pair in Response

当我尝试使用 Postman 通过 Get Request 获取学生详细信息时,我得到了额外的键值对,即(实体:相同对象)存在于其中。请帮助我理解为什么我会得到它以及如何从我的回复中删除它。但是当我尝试打印在 Controller Class(第 1 行)中获取的对象时,它显示了正确的对象。

回复:

{
    "id": 2,
    "name": "ABC Person",
    "age": 28,
    "courses_id": 1,
    "entity": {
        "id": 2,
        "name": "ABC Person",
        "age": 28,
        "courses_id": 1
    }
}

获取请求 URL :

http://localhost:8300/students/ABC Person

REST API 控制器 Class:

@RestController
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    @GetMapping(value="/students/{name}")
    public ResponseEntity<StudentDTO> getStudentDetails(@PathVariable String name){
        StudentDTO student = studentService.getStudentDetails(name);
        System.out.println(student); // LINE 1
        return new ResponseEntity<>(student,HttpStatus.OK);
    }
}

StudentDTO class:

public class StudentDTO {
    private int id;
    private String name;
    private int age;
    private int courses_id;

    //getter and setter methods

    public static StudentDTO valueOf(Student student) {
        StudentDTO studentDTO = new StudentDTO();
        
        studentDTO.setId(student.getId());
        studentDTO.setName(student.getName());
        studentDTO.setAge(student.getAge());
        studentDTO.setCourses_id(student.getCourses_id());
        
        return studentDTO;
    }
    
    public Student getEntity() {
        Student student = new Student();
        
        student.setId(this.id);
        student.setName(this.name);
        student.setAge(this.age);
        student.setCourses_id(this.courses_id);
        
        return student;
    }
}

getEntity上面加一个@JsonIgnore。因为 Jackson(spring 用作消息转换器)将选择 getter 方法,而默认情况下将对象序列化为 json。

@JsonIgnore
public Student getEntity() {
    Student student = new Student();
        
    student.setId(this.id);
    student.setName(this.name);
    student.setAge(this.age);
    student.setCourses_id(this.courses_id);
        
    return student;
}

看起来您正在尝试在 DTO 和 JPA 实体之间进行映射。为了避免在它们之间转换时使用样板代码,您可以使用映射库,如 mapstruct、modelmapper 等...