• 使用fastjson,gson解析null值的时候键保留


    由于业务需求。。。所以查阅资料,总结如下:

    使用gson实现方法:只需要把new Gson()改为:

    new GsonBuilder().serializeNulls().create(); 就可以了
    复制代码
    public class Test {
        public static void main(String[] args) {
            Gson gson= new GsonBuilder().serializeNulls().create();
            Map < String , Object > jsonMap = new HashMap< String , Object>(); 
            jsonMap.put("a",1); 
            jsonMap.put("b",""); 
            jsonMap.put("c",null); 
            jsonMap.put("d","wuzhuti.cn");
            String str = gson.toJson(jsonMap);
            System.out.println(str);
            
            person peson1 = new person();
            peson1.setAge(1);
            peson1.setName(null);
            System.out.println(gson.toJson(peson1));
        }
        
    }
    class person{
        private int age;
        private String name;
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        
    }
    复制代码

    使用fastjson实现方法:只需要再toJsonString的时候加上

    SerializerFeature.WriteMapNullValue 这个参数。
    复制代码
    public class FastJsonTest {
        public static void main(String[] args) {
            /*
             * QuoteFieldNames———-输出key时是否使用双引号,默认为true
             * WriteMapNullValue——–是否输出值为null的字段,默认为false
             * WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
             * WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
             * WriteNullStringAsEmpty—字符类型字段如果为null,输出为"",而非null
             * WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
             */
            Map<String, Object> jsonMap = new HashMap<String, Object>();
            jsonMap.put("a", 1);
            jsonMap.put("b", "");
            jsonMap.put("c", null);
            jsonMap.put("d", "json");
     
            String str = JSONObject.toJSONString(jsonMap);
            // 忽略null输出
            System.out.println(str);
     
            String str2 = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue);
    
            System.out.println(str2);
     
            String json = "{"fail":null,"updateTimestamp":"1484096131863","productName":"json测试"}";
            // 忽略null输出
            System.out.println(JSON.parse(json));
            // 
            System.out.println(JSONObject.toJSON(json));
        }
     
    }
    复制代码

    以上。

  • 相关阅读:
    ROS学习笔记六:xxx.launch文件详解
    XML 基础学习
    Qt之界面(自定义标题栏、无边框、可移动、缩放)
    (转)YV12 and NV12
    FFMPEG的解码后的数据格式
    (转)使用AfxGetMainWnd函数的一个心得
    mout系统流程
    关于多画面窗口切换的刷新重绘问题
    (转)Invalidate、RedrawWindow与UpdateWindow的区别
    (转)关于三星cortex A9 Sate4412 开发板 uboot 启动的一些问题释疑
  • 原文地址:https://www.cnblogs.com/exmyth/p/11595224.html
Copyright © 2020-2023  润新知