时间:2023-02-26 08:36:07 | 栏目:JAVA代码 | 点击:次
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}
使用fastjson将javabean转string时,默认会将值为null的属性过滤掉,
可通过设置SerializerFeature.WriteMapNullValue避免这种情况
String value = JSONObject.toJSONString(objectData, SerializerFeature.WriteMapNullValue);