JavaBean转Json,null值忽略问题


JavaBean转Json,null值忽略问题

问题

下面的代码片段中,result的data属性为null,使用FastJSON将其转为json字符串时,自动忽略了data字段。

response.setContentType("application/json;charset=utf-8");
Result result = Result.builder().build().setData(null).setCode(401).setMsg("token不合法");
response.getWriter().write(JSONObject.toJSONString(result));

返回结果:

{
	"code": 401,
	"msg": "token不合法"
}

解决

如果想保留null值的字段data,可以使用下面的方式

response.setContentType("application/json;charset=utf-8");
Result result = Result.builder().build().setData(null).setCode(401).setMsg("token不合法");
response.getWriter().write(JSONObject.toJSONString(result,SerializerFeature.WriteMapNullValue));

返回结果:

{
	"code": 401,
	"data": null,
	"msg": "token不合法"
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM