JSON.toJSONString 转换json字符串后字段为null的缺失问题

发布时间 2023-06-01 14:28:13作者: 唏嘘-
问题复现:
public static void main(String[] args) {
      Map<String, Object> map = new HashMap<>();
      map.put("code", "123");
      map.put("name", null);
      System.out.println(JSON.toJSONString(map));
}
输出结果:{"code":"123"}

解决方案:转换时增加增加属性   SerializerFeature.WriteMapNullValue
public static void main(String[] args) {
      Map<String, Object> map = new HashMap<>();
      map.put("code", "123");
      map.put("name", null);
      System.out.println(JSON.toJSONString(map, SerializerFeature.WriteMapNullValue));
}  
输出结果:{"code":"123","name":null}