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