java 从对象中删除属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41541488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove attribute from object
提问by Januka samaranyake
I got a list that return from below db call.
我得到了一个从 db 调用返回的列表。
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.
列表包含员工 pojo 类对象。我想删除一个属性,让我们在从休息电话返回时说“员工银行账户号”。
@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?
是否有任何注释或良好做法可以做到这一点?
采纳答案by Aeteros
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:
正如上面的评论中提到的,您不能在运行时删除已编译类的字段。假设您必须从生成的 json 中排除某些字段,我会看到两个选项:
- 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.
- Depending on implementation of your serializer there may be annotations to exclude fields.
@JsonIgnore
may be placed on getter method, if you are using Hymanson (default in spring boot). Second aproach requires significant less code, but the first one is more flexible.
- 创建一个包含要在结果 json 中出现的字段的类,将所需的值从原始对象复制到新创建的对象中。这种方法称为视图模型,它允许您修饰某些对象的数据,从而隐藏敏感数据不被暴露。
- 根据您的序列化程序的实现,可能会有注释来排除字段。
@JsonIgnore
如果您使用的是 Hymanson(spring boot 中的默认设置),则可能会放在 getter 方法上。第二种方法需要的代码要少得多,但第一种方法更灵活。