英文:
How to apply json ignore annotation on a rest controller method endpoint in spring boot?
问题
我有一个名为Customer的类
Customer{
private int ID;
private IDCard idCard;
}
以及IDCard.java
IDCard{
private int id;
private int score;
}
我有两个端点,endpoint01和endpoint02。
因此,当我使用endpoint01添加客户时,提供分数是必需的。但是当我使用endpoint02添加客户时,分数不是必需的。
由于我在两个端点的控制器方法中都使用了相同的客户模型,Jackson会抛出错误,因为在endpoint02中我没有提供分数。
在这种情况下,很明显我不能在我的IDCard模型中应用json ignore。那么,我该如何告诉我的endpoint02如果json对象中不存在该字段,则忽略score字段,并且仅在字段在json对象中存在时进行反序列化。
这是我的endpoint02
@RequestMapping(method=RequestMethod.POST, value="/add", headers="Accept=application/json")
public @ResponseBody Map<String, List<String>> add(@RequestBody Customer customer) {
return customerSvc.add(customer);
}
英文:
I have a class called Customer
Customer{
private int ID;
private IDCard idCard;
}
and IDCard.Java
IDCard{
private int id;
private int score;
}
I have two endpoints, endpoint01 and endpoint02.
So when I add a customer using endpoint01, providing score is mandatory. But when I add customer using endpoint02, score is not mandatory.
As I am using Same customer model in both endpoint's controller method, Jackson throws error because on endpoint02 I didn't provide score.
In this case its clear that I can not apply json ignore in my IDCard model. 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.
This is my endpoint02
@RequestMapping(method=RequestMethod.POST, value="/add",headers="Accept=application/json")
public @ResponseBody Map<String,List<String>> add(@RequestBody Customer customer) {
return customerSvc.add(customer);
}
答案1
得分: 2
以下是翻译好的内容:
你想要的是在你的POJO上进行注解,而不是在你的ENDPOINT上。
IDCard{
@JsonProperty(value="id" , required=false)
private int id;
@JsonProperty(value="score" , required=false)
private int score;
}
这将使得在对对象进行反序列化时可以避免处理这些字段。
注意:请注意封装性。
英文:
what you want is annotation on your POJO and not on your 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.
答案2
得分: 2
你可以在特定的属性上应用忽略注释。
英文:
You can apply ignore annotation on the specific property.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论