• 比较json和fastjson的put()


    首先,分别运行下面两段json和fastjson的代码:

    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class Jsons {
    	public static void main(String[] args) throws JSONException {
    		JSONObject jsons = new JSONObject();
    		jsons.put("key","123");
    		
    		System.out.println("#1:"+ jsons.toString());
    		System.out.println("#2:"+ new JSONObject().put("key", "123").toString());
    	}
    }
    
    import com.alibaba.fastjson.JSONObject;
    
    public class FastJsons {
    	public static void main(String[] args) {
    		JSONObject fastJsons = new JSONObject();
    		fastJsons.put("kye", "456");
    		
    		System.out.println("#1:" + fastJsons.toString());
    		System.out.println("#2:" + new JSONObject().put("key:", "456").toString() );
    	}
    	
    }
    

    观察两个类,貌似没有什么区别,但是运行之后,控制台打印的结果却是:

    // json
    #1:{"key":"123"}
    #2:{"key":"123"}
    
    // fastjson
    #1:{"kye":"456"}
    Exception in thread "main" java.lang.NullPointerException
    	at day1.FastJsons.main(FastJsons.java:11)
    

    我们发现fastjson中报了异常,然后我们来查看各自put()源码:

    // json
    /*      */   public JSONObject put(String key, Object value)
    /*      */     throws JSONException
    /*      */   {
    /* 1069 */     if (key == null) {
    /* 1070 */       throw new JSONException("Null key.");
    /*      */     }
    /* 1072 */     if (value != null) {
    /* 1073 */       testValidity(value);
    /* 1074 */       map.put(key, value);
    /*      */     } else {
    /* 1076 */       remove(key);
    /*      */     }
    /* 1078 */     return this;
    /*      */   }
    
    // fastjson
    /*     */   public Object put(String key, Object value) {
    /* 316 */     return map.put(key, value);
    /*     */   }
    
  • 相关阅读:
    webpack详解
    扩展运算符及其在vuex的辅助函数里的应用详解
    react组件间传值详解
    类的构造函数(3)
    类构造函数(4)
    new delete
    类的构造函数(1)
    类的构造函数(2)
    类的继承(1)
    静态成员数据与函数
  • 原文地址:https://www.cnblogs.com/52liming/p/9537981.html
Copyright © 2020-2023  润新知