标签:create unit public sys ignore ons object 操作 lib
环境:
jdk: openjdk11
操作系统: windows 10教育版1903
目的:
如题,当一个对象里有些属性值为null 的不想参与json序列化时,可以添加如下注解
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonIgnore;
//这个是类注解,表示该类实例化的对象里,值为null的字段不参与序列化
@JsonInclude(JsonInclude.Include.NON_NULL) @Setter @Getterpublic class AbilityEntity { private Long id; private String name;
//JsonIgnore注解 表示 每次json处理都忽略createTime属性
@JsonIgnore
private Long createTime;//unix时间戳,ms
}
以下是单元测试(DemoApplicationTests.java):
package com.example.demo; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Getter; import lombok.Setter; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DemoApplicationTests { @Test void contextLoads() { AbilityEntity ability = new AbilityEntity(); ability.setId(1L); System.out.println(JSONObject.toJSON(ability)); ability.setName("");//只要不是null, 都不会被忽略 System.out.println(JSONObject.toJSON(ability)); } @JsonInclude(JsonInclude.Include.NON_NULL) @Setter @Getter public class AbilityEntity{ private Long id; private String name; } }
console
{"id":1}
{"name":"","id":1}
标签:create unit public sys ignore ons object 操作 lib
原文地址:https://www.cnblogs.com/tu13/p/java_springboot_entity_ignorenullproperty.html