【问题标题】:Ignore null fields when DEserializing JSON with Gson or Jackson使用 Gson 或 Jackson 反序列化 JSON 时忽略空字段
【发布时间】:2016-07-26 22:43:35
【问题描述】:

我知道在将对象序列化为 JSON 时,有很多关于跳过具有空值的字段的问题。 在将 JSON 反序列化为对象时,我想跳过/忽略具有空值的字段。

考虑类

public class User {
    Long id = 42L;
    String name = "John";
}

和 JSON 字符串

{"id":1,"name":null}

做的时候

User user = gson.fromJson(json, User.class)

我希望 user.id 为“1”,user.name 为“约翰”。

这对于 Gson 或 Jackson 是否有可能以一般方式(没有特殊的 TypeAdapters 或类似的)?

【问题讨论】:

  • user.name 将如何成为“John”。如果示例 json 有 "name":null ?您是在问它是否可以跳过 Json 中的 Null 值而不覆盖类中的默认值?
  • @jeffporter 是的,这正是问题所在。
  • 你找到了一个很好的解决方案吗?
  • @jayeffkay 不。
  • 我也有同样的问题

标签: java json jackson gson deserialization


【解决方案1】:

虽然不是最简洁的解决方案,但使用 Jackson,您可以使用自定义 @JsonCreator 自行设置属性:

public class User {
    Long id = 42L;
    String name = "John";

    @JsonCreator
    static User ofNullablesAsOptionals(
            @JsonProperty("id") Long id,
            @JsonProperty("name") String name) {
        User user = new User();
        if (id != null) user.id = id;
        if (name != null) user.name = name;
        return user;
    }
}

【讨论】:

    【解决方案2】:

    我所做的是在 getter 上设置默认值

    public class User {
        private Long id = 42L;
        private String name = "John";
    
        public getName(){
           //You can check other conditions
           return name == null? "John" : name;
        }
    }
    

    我想这对许多领域来说会很痛苦,但它适用于字段数量较少的简单情况

    【讨论】:

      【解决方案3】:

      要跳过使用 TypeAdapters,我会让 POJO 在调用 setter 方法时进行一次空值检查。

      或者看看

      @JsonInclude(value = Include.NON_NULL)
      

      注解需要在类级别,而不是方法级别。

      @JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case 
      public static class RequestPojo {
          ...
      }
      

      对于反序列化,您可以在类级别使用以下操作。

      @JsonIgnoreProperties(ignoreUnknown = true)

      【讨论】:

      • @JsonInclude(value = Include.NON_NULL) 似乎只在序列化时有效,在反序列化时无效。
      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      相关资源
      最近更新 更多