Search code examples
javaspring-bootspring-restcontrollerspring-rest

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


When I try to get student details by Get Request using Postman, I'm getting extra key-value pair i.e(entity: same-object) present in it. Please help me understand why I'm getting that and how can I remove that from my Response. But when I try to print the object which is fetched in Controller Class (in Line 1) it shows the correct object.

Response :

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

Get Request URL :

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

REST API Controller 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;
    }
}

Solution

  • Add a @JsonIgnore above getEntity. Because Jackson (which spring use as messageconverter) will pick getter method while seriliaze object to json by default.

    @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;
    }
    

    Look like you are trying to map between DTO and JPA Entity. To avoid boilerplate code while converting between them, you can use mapping libraries like mapstruct, modelmapper, etc...