mthoutai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

fastjson null 值处理

偶然用到fastjson转换json 在前台用js解析竟然某些字段没有,曾经用过gson。联想到是不是相似gson默认将null值不显示了,找了下资料果真如此

直接上代码吧

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;


public class Test2 {

    /**
     * @param args
     */
    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("xyw",1);  
        jsonMap.put("123","");  
        jsonMap.put("xuyw",null);  
        jsonMap.put("xywa","css");  

        String str = JSONObject.toJSONString(jsonMap);  
        System.out.println(str);

        String str2 = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue);  
        System.out.println(str2);
    }

}

输出结果

{"123":"","xyw":1,"xywa":"css"}
{"123":"","xuyw":null,"xyw":1,"xywa":"css"}
<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('
    ').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('
  • ').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
---

相关学习推荐

根据本文内容,精选以下优质课程:

  1. Android开发高手课
    ‍ 张绍文 | 突破Android开发进阶瓶颈
  2. Java核心技术面试精讲
    ‍ 杨晓峰 | 以面试题为切入点,有效提升Java内功
  3. 玩转Spring全家桶
    ‍ 丁雪丰 | 全面掌握Spring生态体系

开发资源

posted on 2017-06-30 21:45  mthoutai  阅读(2743)  评论(0)    收藏  举报