如何在Spring Boot的REST控制器方法端点上应用JSON忽略注释?

huangapple go评论94阅读模式
英文:

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=&quot;/add&quot;,headers=&quot;Accept=application/json&quot;)
public @ResponseBody Map&lt;String,List&lt;String&gt;&gt; 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=&quot;id&quot; , required=false)
   private int id;
   @JsonProperty(vaue=&quot;score&quot; , 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.

huangapple
  • 本文由 发表于 2020年9月22日 13:11:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64003411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定