jackson @JsonInclude注解(null属性不出现在json中) 作者:马育民 • 2020-10-03 13:07 • 阅读:10192 # 案例 在前后台分离式开发中,后台要向前端递json数据,很多前端程序员不想json中有null的数据,如下: ``` {"code":0,"msg":"hello",data:null} ``` `data:null`不要出现在json串中 # 解决 `@JsonInclude`注解的作用:java对象转json字符串时,当对象的属性为null时,该属性不会出现在json字符串中 # 例子 ``` @JsonInclude(JsonInclude.Include.NON_NULL) public class JsonResult { /** * code: * 0:表示成功 */ private int code; private String msg; private T data; public JsonResult() { } public JsonResult(int code,String msg){ this.code=code; this.msg=msg; } public JsonResult(int code,T data){ this.code=code; this.data=data; } public JsonResult(int code,String msg,T data){ this.code=code; this.msg=msg; this.data=data; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } } ``` ### 测试1 将java对象转换json字符串 ``` JsonResult jr=new JsonResult(); jr.setCode(0); jr.setMsg("hello"); ObjectMapper om=new ObjectMapper(); String json=om.writeValueAsString(jr); System.out.println(json); ``` 执行结果: ``` {"code":0,"msg":"hello"} ``` 因为data为null,所以转换时不包含 ### 测试2 将java对象转换json字符串 ``` JsonResult jr=new JsonResult(); jr.setCode(0); //jr.setMsg("hello"); ObjectMapper om=new ObjectMapper(); String json=om.writeValueAsString(jr); System.out.println(json); ``` 执行结果: ``` {"code":0} ``` 因为msg和data为null,所以转换时不包含 原文出处:http://malaoshi.top/show_1EF6N4F2EDrd.html