fastjson过滤和保留null值的问题
源代码:
try {
log.info("请求头中获取到的令牌的键:{}", token);
Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
return true;
} catch (Exception ex) {
// 不通过,响应401状态码
response.setStatus(401);
// 设置返回格式为JSON
response.setHeader("Content-Type", "application/json");
if(token == null) {
String jsonString = JSON.toJSONString(Result.error("token empty"));
log.info("token为空返回值:{}", jsonString);
response.getWriter().write(jsonString);
} else {
String jsonString = JSON.toJSONString(Result.error("token error"));
log.info("token为空返回值:{}", jsonString);
response.getWriter().write(jsonString);
}
return false;
}
返回值:
{
"code": 0,
"msg": "token empty"
}
解决办法:
JSON.toJSONString(Result.error("token error"), SerializerFeature.WriteMapNullValue);
在JSON.toJSONString
添加第二个参数SerializerFeature.WriteMapNullValue
修改后:
try {
log.info("请求头中获取到的令牌的键:{}", token);
Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
return true;
} catch (Exception ex) {
// 不通过,响应401状态码
response.setStatus(401);
// 设置返回格式为JSON
response.setHeader("Content-Type", "application/json");
if(token == null) {
String jsonString = JSON.toJSONString(Result.error("token empty"), SerializerFeature.WriteMapNullValue);
log.info("token为空返回值:{}", jsonString);
response.getWriter().write(jsonString);
} else {
String jsonString = JSON.toJSONString(Result.error("token error"), SerializerFeature.WriteMapNullValue);
log.info("token为空返回值:{}", jsonString);
response.getWriter().write(jsonString);
}
return false;
}
返回值:
{
"code": 0,
"data": null,
"msg": "token empty"
}
阅读剩余
THE END