日期:2014-05-16  浏览次数:20420 次

JSON-LIB 中的null,引发的问题

java中的null对象和"null"字符串,JSonObject会默认对这些数据进行处理。

考虑到这样一种场景:发送方和接收方通过json格式数据进行交互

 // key = null,这种键值对会直接被json-lib忽略
    // key = "null",这种值会被json-lib转换null
    public static String sendJmsString()
    {
        JSONObject selfObj = new JSONObject();
        selfObj.put("name", "aty");
        selfObj.put("address", "null");
        selfObj.put("school", null);
        selfObj.put("home", "");

        return selfObj.toString();
    }

?

public static void receiveJmsString(String msg)
    {
        JSONObject selfObj = JSONObject.fromObject(msg);
        
        Object name = selfObj.get("name");
        Object home = selfObj.get("home");
        
        //net.sf.json.JSONNull
        Object address = selfObj.get("address");
        String strAddress = selfObj.getString("address");
        
        
        System.out.println(name.getClass());
        System.out.println(address.getClass());
        System.out.println(home.getClass());
        
        
        System.out.println(address == null);//false
        System.out.println("null".equals(strAddress));//true
    }

?

?

测试代码如下:

 public static void main(String[] args)
    {
        String msg = sendJmsString();
        
        // null是json中的关键字
        //msg = {"name":"aty","address":null,"home":""}
        System.out.println("msg = " + msg);
        
        receiveJmsString(msg);
    }

?

?

由此可见在是json进行数据传递的时候,要特殊注意null对象和"null"这种键值对,不然会出现错误