fastjson中的坑 map中空字符问题
JSON.toJSONString中序列化map中的空字符串会出现空对象问题
Map<String,String> map = new HashMap<>(); map.put("aaa",null); map.put("bbb",null); map.put("ccc",null); map.put("ddd",null); System.out.println(map.toString());//打印结果:{aaa=null, ccc=null, bbb=null, ddd=null} String s = JSONObject.toJSONString(map); System.out.println(s);//打印结果:{} 造成空对象
解决方法:
通过String s = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue)
Map<String,String> map = new HashMap<>(); map.put("aaa",null); map.put("bbb",null); map.put("ccc",null); map.put("ddd",null); System.out.println(map.toString()); String s = JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue);//打印结果:{aaa=null, ccc=null, bbb=null, ddd=null}
System.out.println(s);//打印结果:{"aaa":null,"ccc":null,"bbb":null,"ddd":null}
Json转某个对象时,使用这个方法
DeviceLaserStatus deviceLaserStatus = JSON.parseObject(objectToJson, new TypeReference<DeviceLaserStatus>() {});