[英]How to apply json ignore annotation on a rest controller method endpoint in spring boot?
I have a class called Customer我有一个班级叫客户
Customer{
private int ID;
private IDCard idCard;
}
and IDCard.Java和 IDCard.Java
IDCard{
private int id;
private int score;
}
I have two endpoints, endpoint01 and endpoint02.我有两个端点,endpoint01 和 endpoint02。 So when I add a customer using endpoint01, providing score is mandatory.
因此,当我使用 endpoint01 添加客户时,必须提供分数。 But when I add customer using endpoint02, score is not mandatory.
但是当我使用 endpoint02 添加客户时,分数不是强制性的。
As I am using Same customer model in both endpoint's controller method, Jackson throws error because on endpoint02 I didn't provide score.当我在两个端点的控制器方法中使用相同的客户模型时,Jackson 抛出错误,因为在端点 02 上我没有提供分数。 In this case its clear that I can not apply json ignore in my IDCard model.
在这种情况下,很明显我不能在我的 IDCard 模型中应用 json ignore 。 So how can I tell my endpoint02 to ignore score field if it is not present and deserialize only if the field is present in the json object.
那么如何告诉我的 endpoint02 忽略 score 字段,如果它不存在,并且仅当该字段存在于 json 对象中时才反序列化。
This is my endpoint02这是我的端点02
@RequestMapping(method=RequestMethod.POST, value="/add",headers="Accept=application/json")
public @ResponseBody Map<String,List<String>> add(@RequestBody Customer customer) {
return customerSvc.add(customer);
}
what you want is annotation on your POJO and not on your ENDPOINT您想要的是 POJO 上的注释,而不是 ENDPOINT 上的注释
IDCard{
@JsonProperty(vaue="id" , required=false)
private int id;
@JsonProperty(vaue="score" , required=false)
private int score;
}
this will enable your fields to be avoided while deserializing the object.这将使您在反序列化对象时避免使用字段。
Note : take care of encapsulation.注意:注意封装。
您可以在特定属性上应用忽略注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.