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不合法"
}