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