使用JSONObject.toJSONString 过滤掉值为空的key
JSONObject.toJSONString 过滤值为空的key
情况
public static String getJsonResult(int status, String msg, Object data){undefined
Map<String, Object> resultMap=new HashMap<String, Object>();
resultMap.put("status", status);
resultMap.put("msg", msg);
resultMap.put("data", data);
return JSONObject.toJSONString(resultMap);
}
public static void main(String[] args) {undefined
System.out.println(getJsonResult(1, "success", null));
}结果
{"msg":"success","status":1}
从输出结果可以看出,null对应的key已经被过滤掉;这明显不是我们想要的结果,这时我们就需要用到fastjson的SerializerFeature序列化属性
也就是这个方法
JSONObject.toJSONString(Object object, SerializerFeature... features)
public static String getJsonResult(int status, String msg, Object data){undefined
Map<String, Object> resultMap=new HashMap<String, Object>();
resultMap.put("status", status);
resultMap.put("msg", msg);
resultMap.put("data", data);
return JSONObject.toJSONString(resultMap,SerializerFeature.WriteMapNullValue);
}public static void main(String[] args) {undefined
System.out.println(getJsonResult(1, "success", null));
}结果
{"msg":"success","data":null,"status":1}
JSONObject.toJSONString自动过滤空值
使用fastjson将javabean转string时,默认会将值为null的属性过滤掉,
可通过设置SerializerFeature.WriteMapNullValue避免这种情况
String value = JSONObject.toJSONString(objectData, SerializerFeature.WriteMapNullValue);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
- String转JSONObject的两种方式
- Java中如何将String转JSONObject
- 关于JSONObject.toJSONString出现地址引用问题
- 利用JSONObject.toJSONString()包含或排除指定的属性
- JSONObject toJSONString错误的解决
- 解决JSONObject.toJSONString()输出null的问题
- Java使用fastjson对String、JSONObject、JSONArray相互转换
- 详解Java中String JSONObject JSONArray List<实体类>转换
- 解决String字符串转JSONObject顺序不对的问题
相关文章
springboot+element-ui实现多文件一次上传功能
这篇文章主要介绍了springboot+element-ui多文件一次上传功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-06-06
Spring Cloud出现Options Forbidden 403问题解决方法
本篇文章主要介绍了Spring Cloud出现Options Forbidden 403问题解决方法,具有一定的参考价值,有兴趣的可以了解一下2017-11-11
SpringBoot Maven打包插件spring-boot-maven-plugin无法解析原因
spring-boot-maven-plugin是spring boot提供的maven打包插件,本文主要介绍了SpringBoot Maven打包插件spring-boot-maven-plugin无法解析原因,具有一定的参考价值,感兴趣的可以了解一下2024-03-03


最新评论