1

I am using spring boot for a project. The response json contains all the fields of the object , but i am expecting only the fields which i want.

For example, consider below class

public class Employee {

private String id;

private String name;

private String address;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

}

And the controller end point,

@GetMapping("/endpoint")
public Employee getEmpDetail() {
    Employee emp = new Employee();
    emp.setId("1");
    emp.setName("Manikandan");
    emp.setAddress("Karur");
    return emp;
}

By default , we will get all the fields in response , here i am expecting only the name field when i hit the url like localhost:8080/endpoint?filter=name

Manikandan
  • 121
  • 11

1 Answers1

-3

You can try with return type as ResponseEntity<String>

public ResponseEntity<String> getEmpDetail() {

        Person person = new Person();
        person.setId("1");
        person.setName("AB");
        person.setAddress("Delhi");
        return new ResponseEntity<String>(person.getName(), HttpStatus.OK);
}

You can filter out the response String as per your requirement like name for localhost:8080/endpoint?filter=name

For address i.e. localhost:8080/endpoint?filter=address, you can go like

return new ResponseEntity<String>(person.getAddress(), HttpStatus.OK);
Harshit
  • 5,147
  • 9
  • 46
  • 93