不同Json工具对空串和NULL的序列号处理:net.sf.json 和 fastjson

net.sf.json 和 fastjson 对于空串和NULL的处理:

1、测试代码

package com.TestMain;
 
import com.alibaba.fastjson.JSON;
 
import java.util.HashMap;
import java.util.Map;
 
public class TestTest {
 
    public static void main(String args[]) throws Exception {
 
        String sDesc = "";
        Map<String, String> map = new HashMap<String, String>();
        map.put("test", "test");
        map.put("str", null);
        System.out.println("测试:null");
        System.out.println("ALIBAB:"+JSON.toJSONString(map));
        System.out.println("net:"+net.sf.json.JSONObject.fromObject(map).toString());
        System.out.println("=====");
 
        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("test", "test");
        map2.put("str", "null");
        System.out.println("测试:null字符串");
        System.out.println("ALIBAB:"+JSON.toJSONString(map2));
        System.out.println("net:"+net.sf.json.JSONObject.fromObject(map2).toString());
        System.out.println("=====");
 
        Map<String, String> map3 = new HashMap<String, String>();
        map3.put("test", "test");
        map3.put("str", "");
        System.out.println("测试:空白字符串");
        System.out.println("ALIBAB:"+JSON.toJSONString(map3));
        System.out.println("net:"+net.sf.json.JSONObject.fromObject(map3).toString());
        System.out.println("=====");
 
    }
 
}

2、测试结果:

测试:null
ALIBAB:{"test":"test"}
net:{"str":null,"test":"test"}
=====
测试:null字符串
ALIBAB:{"str":"null","test":"test"}
net:{"str":null,"test":"test"}
=====
测试:空白字符串
ALIBAB:{"str":"","test":"test"}
net:{"str":"","test":"test"}
=====

3、总结:

  • fastJson 根据传入的对象进行序列化,是字符串就是字符串,是NULL就是NULL。序列化结果不包含NULL。
  • net.sf.json 会将NULL和NULL字符串都作为NULL处理。序列化结果包含NULL,但是其值也是NULL(不是NULL字符串)。

4、注:Maven中引入net.sf.json的方式

  1. maven 无法引入 net.sf.json 的解决方法 - vili_sky 的博客 - CSDN 博客
  2. json-lib 的 maven dependency - 海山 - 博客园
posted @ 2019-09-10 16:18  不无聊  阅读(776)  评论(0编辑  收藏  举报