java json 序列化对象空值不处理_Jackson序列化:忽略空值(或null)

我当前正在使用杰克逊2.1.4,并且在将对象转换为JSON字符串时,在忽略字段方面遇到一些麻烦。

这是我的类,它充当要转换的对象:

public class JsonOperation {

public static class Request {

@JsonInclude(Include.NON_EMPTY)

String requestType;

Data data = new Data();

public static class Data {

@JsonInclude(Include.NON_EMPTY)

String username;

String email;

String password;

String birthday;

String coinsPackage;

String coins;

String transactionId;

boolean isLoggedIn;

}

}

public static class Response {

@JsonInclude(Include.NON_EMPTY)

String requestType = null;

Data data = new Data();

public static class Data {

@JsonInclude(Include.NON_EMPTY)

enum ErrorCode { ERROR_INVALID_LOGIN, ERROR_USERNAME_ALREADY_TAKEN, ERROR_EMAIL_ALREADY_TAKEN };

enum Status { ok, error };

Status status;

ErrorCode errorCode;

String expiry;

int coins;

String email;

String birthday;

String pictureUrl;

ArrayList performer;

}

}

}

这是我如何转换它:

ObjectMapper mapper = new ObjectMapper();

mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

JsonOperation subscribe = new JsonOperation();

subscribe.request.requestType = "login";

subscribe.request.data.username = "Vincent";

subscribe.request.data.password = "test";

Writer strWriter = new StringWriter();

try {

mapper.writeValue(strWriter, subscribe.request);

} catch (JsonGenerationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (JsonMappingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

这是输出:

{"data":{"birthday":null,"coins":null,"coinsPackage":null,"email":null,"username":"Vincent","password":"test","transactionId":null,"isLoggedIn":false},"requestType":"login"}

如何避免这些空值?我只想获取“订阅”目的所需的信息!

这正是我要寻找的输出:

{"data":{"username":"Vincent","password":"test"},"requestType":"login"}

我还尝试了@JsonInclude(Include.NON_NULL)并将所有变量都设置为null,但是它也不起作用!感谢您的帮助!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值