2016-04-06 204 views
5

我知道在将对象序列化为JSON时跳过带空值的字段有很多问题。 当将JSON反序列化为对象时,我想跳过/忽略具有空值的字段。使用Gson或Jackson反序列化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或杰克逊在一般的方式(没有特殊的TypeAdapter或类似)?

+0

user.name将如何成为'John'。如果示例json有“name”:null?你问是否可以跳过Json中的空值并且不覆盖类中的默认值? –

+0

@jeffporter是的,这正是问题所在。 – FWeigl

+0

你有没有找到一个漂亮的解决方案呢? – jayeffkay

回答

0

要跳过使用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 =真)

+3

@JsonInclude(value = Include.NON_NULL)似乎只在序列化时才起作用,而不是在反序列化时起作用。 – FWeigl

0

我做了什么在我的情况是设置在吸气

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

    public getName(){ 
     //You can check other conditions 
     return name == null? "John" : name; 
    } 
} 

我想这将是许多领域的一个痛苦的默认值,但它的工作原理在数量较少的字段的简单情况下

0

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

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

    @JsonCreator 
    static User ofNullablesAsOptionals(
      @JsonProperty("id") Long id, 
      @JsonProperty("name") String name) { 
     if (id != null) this.id = id; 
     if (name != null) this.name = name; 
    } 
} 
相关问题