【问题标题】:How to apply json ignore annotation on a rest controller method endpoint in spring boot?如何在spring boot中的rest控制器方法端点上应用json忽略注释?
【发布时间】:2021-01-08 04:56:44
【问题描述】:

我有一个名为 Customer 的类

Customer{
   private int ID;
   private IDCard idCard;
}

和IDCard.Java

IDCard{
   private int id;
   private int score;
}

我有两个端点,端点01 和端点02。 因此,当我使用 endpoint01 添加客户时,必须提供分数。但是当我使用 endpoint02 添加客户时,分数不是强制性的。

当我在两个端点的控制器方法中使用相同的客户模型时,Jackson 会抛出错误,因为在端点02 我没有提供分数。 在这种情况下,很明显我不能在我的 IDCard 模型中应用 json ignore。那么如何告诉我的endpoint02 忽略 score 字段,如果它不存在,并且只有当 json 对象中存在该字段时才反序列化。

这是我的端点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);
}

【问题讨论】:

    标签: java spring-boot spring-mvc jackson


    【解决方案1】:

    您可以在特定属性上应用忽略注释。

    【讨论】:

      【解决方案2】:

      您想要的是 POJO 上的注释,而不是 ENDPOINT 上的注释

      IDCard{
      
         @JsonProperty(vaue="id" , required=false)
         private int id;
         @JsonProperty(vaue="score" , required=false)
         private int score;
      
      }
      

      这将使您在反序列化对象时避免使用您的字段。

      注意:注意封装。

      【讨论】:

        猜你喜欢
        • 2018-07-07
        • 2020-10-27
        • 2017-05-04
        • 2017-06-24
        • 2020-04-27
        • 2017-04-26
        • 2015-04-30
        • 1970-01-01
        • 2014-10-06
        相关资源
        最近更新 更多