Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove attribute from object

I got a list that return from below db call.

List<employee> list = empolyeeRepository.findByEmployeeId(id);

List contains employee pojo class object. I want to remove one attribute let's say "employee bank account no" when returning from rest call.

@RequestMapping(value = "/employeeInformation/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Employee> getEmployeeInformation(@PathVariable("id") String id) throws Exception {
    return empolyeeRepository.findByEmployeeId(id);
}

Is there any annotation or good practice to do that?

like image 728
Januka samaranyake Avatar asked Mar 11 '23 05:03

Januka samaranyake


2 Answers

As it mentioned in comments above, you cant remove fields of compiled class at runtime. Assuming you have to exclude some field from generated json, there I see two options:

  1. Create a class with fields you want to be present in resulting json, copy required values from original object to a new created. This approach is called view model and allows you to decorate some object's data, hiding sensitive data from being exposed.
  2. Depending on implementation of your serializer there may be annotations to exclude fields. @JsonIgnore may be placed on getter method, if you are using Jackson (default in spring boot). Second aproach requires significant less code, but the first one is more flexible.
like image 97
Aeteros Avatar answered Mar 31 '23 02:03

Aeteros


Try @JsonIgnore to ignore properties from serialization and de-serialization. Here is the link to the docs

like image 22
Abdullah Khan Avatar answered Mar 31 '23 02:03

Abdullah Khan