使用 Gson 或 Jackson 反序列化 JSON 时忽略空字段

问题描述 投票:0回答:4

我知道在将对象序列化为 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
为“John”。

这对于 Gson 或 Jackson 以一般方式可能吗(没有特殊的

TypeAdapter
或类似的)?

java json jackson gson deserialization
4个回答
4
投票

很多时间过去了,但是如果你像我一样遇到这个问题并且你至少使用 Jackson 2.9 那么你可以解决它的一种方法是使用 JsonSetterNulls.SKIP:

public class User {
    private Long id = 42L;
    
    @JsonSetter(Nulls.SKIP)
    private String name = "John";

    ... cooresponding getters and setters  
   
}

这样,当遇到null时,setter就不会被调用。

注意:更多详细信息可以在这里找到。


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;
    }
}

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


-1
投票

要跳过使用 TypeAdapters,我会让 POJO 在调用 setter 方法时执行 null 检查。

或者看看

@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)


-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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.