使用Gson或Jackson解序JSON时,请忽略空字段 [英] Ignore null fields when DEserializing JSON with Gson or Jackson

查看:693
本文介绍了使用Gson或Jackson解序JSON时,请忽略空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



考虑类

  public class User {
长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 s或类似的)虽然不是最简洁的解决方案,但您可以使用自定义 @来处理属性设置, JsonCreator

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

@JsonCreator
静态用户ofNullablesAsOptionals(
@JsonProperty(id)Long id,
@JsonProperty(name)字符串名称){
用户用户=新用户();
if(id!= null)user.id = id;
if(name!= null)user.name = name;
返回用户;
}
}


I know there's lots of questions about skipping fields with a null value when serializing objects to JSON. I want to skip / ignore fields with null values when deserializing JSON to an object.

Consider the class

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

and the JSON string

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

When doing

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

I want user.id to be '1' and user.name to be 'John'.

Is this possible with either Gson or Jackson in a general fashion (without special TypeAdapters or similar)?

解决方案

Albeit not the most concise solution, with Jackson you can handle setting the properties yourself with a custom @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;
    }
}

这篇关于使用Gson或Jackson解序JSON时,请忽略空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆