@JsonInclude
应用范围: 注解 方法 字段 接口 方法参数
作用: 作用过在类上, 如果类中的字段值为Null 则返回值中不包含Null值字段
代码示例:
Demo1:
@Data
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class TestDemo {
private String a;
private String b;
}
请求:
@GetMapping("/test")
public TestDemo test() {
TestDemo testDemo = new TestDemo();
testDemo.setA("a");
return testDemo;
}
响应:
{
"code": 0,
"message": "成功",
"data": {
"a": "a"
}
}
Demo2: //没有赋值返回为空对象
请求:
@GetMapping("/test")
public TestDemo test() {
TestDemo testDemo = new TestDemo();
return testDemo;
}
响应:
{
"code": 0,
"message": "成功",
"data": {
}
}
@JsonIgnorn
应用范围: 注解 方法 构造函数 字段
作用: 应用的字段上 默认值为true , 如果应用在字段上则返回值为Null时 , 返回值不包含为null值
代码示例:
Demo1:
@Data
public class TestDemo {
private String a;
@JsonIgnore
private String b;
}
请求:
@GetMapping("/test")
public TestDemo test() {
TestDemo test = new TestDemo();
test.setA("a");
return test;
}
返回值:
{
"code": 0,
"message": "成功",
"data": {
"a": "a"
}
}
Demo2:
@Data
public class TestDemo {
private String a;
@JsonIgnore(value = false)
private String b;
}
请求:
@GetMapping("/test")
public TestDemo test() {
TestDemo test = new TestDemo();
test.setA("a");
return test;
}
返回值:
{
"code": 0,
"message": "成功",
"data": {
"a": "a",
"b": "b"
}
}
@JsonIgnoreProperties
应用范围: 注解 接口 类 方法 构造 字段
属性:
value : 返回值中过滤Null值 禁止序列化和反序列化
ignoreUnknown: true json字符串格式化为javabean时 忽略json字符串中多余的字段以免报错
allowSetters = true(默认是false),允许反序列化。
allowGetters= true(默认是false),允许序列化。
@JsonIgnoreProperties(value = {})
作用: 应用在类上过滤字段
代码示例:
Demo1:
@Data
@JsonIgnoreProperties(value={"b","a"})
public class TestDemo {
private String a;
private String b;
}
@GetMapping("/test")
public TestDemo test() {
TestDemo test = new TestDemo();
test.setA("a");
return test;
}
返回值:
@JsonIgnoreProperties 过滤了所有字段 所以返回值为null
{
"code": 0,
"message": "成功",
"data": {}
}
@JsonProperty
应用范围: 注解 字段 方法 方法参数
作用: 引用在字段上 修改了字段名不会影响反序列化.
代码示例
public class TestDemo {
@JsonProperty("b")
private Long a;
public static void main(String[] args) throws IOException {
String s="{"
+ "\"b\":\"b\""
+ "}";
TestDemo testDemo = JsonUtil.jsonStr2Bean(s, TestDemo.class);
}