0%

JSON 处理 (三): 不返回 null 字段 @JsonInclude

后端返回给前端 JSON 格式的对象数据中,当对象的字段为 NULL 时,该字段也会写入 JSON 返回;而很多时候前端期望后端只返回对象中非 null 的字段数据。在 Jackson 框架中提供了 @JsonInclude 注解以实现该功能

不返回 null 字段数据

在相关对象的类上添加 @JsonInclude 注解,设定值为 NON_NULL

1
2
3
4
5
6
7
8
9
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Student
{
private int id;
private String username;
private String sex;
private String address;
...
}

则 HTTP Response 返回的该类的对象的 JSON 数据如下所示,无为 null 的字段

1
2
3
4
5
{
"id": 0,
"username": "Kallen",
"sex": "female"
}

返回 null 字段数据

在相关对象的类上添加 @JsonInclude 注解,设定值为 ALWAYS

1
@JsonInclude(JsonInclude.Include.ALWAYS)

则 HTTP Response 返回的该类的对象的 JSON 数据如下所示,其中包含 null 的字段

1
2
3
4
5
6
{
"id": 0,
"username": "Kallen",
"sex": "female",
"address": null
}

Note

  • 该注解不设定值的情况下,默认使用 ALWAYS
请我喝杯咖啡捏~

欢迎关注我的微信公众号:青灯抽丝

来发评论吧~
Powered By Valine
v1.5.2