场景
首先看两段代码 //======================第一段============================= import org.json.JSONObject; public class JSONTest { public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("key", "123");
System.out.println("#1:"+json.toString());
System.out.println("#2:"+ new JSONObject().put("key", "123").toString() );
}
} //============================第二段======================= import com.alibaba.fastjson.JSONObject; public class JSONTest {
public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("key", "123");
System.out.println("#1:"+json.toString());
System.out.println("#2:"+ new JSONObject().put("key", "123").toString() );
}
} //===================================================
很明显的看出这两部分只是引入的jar不同而已。那么运行起来效果能不能一样呢? 答案肯定是不同的。 首先json.org给出的jar包能够正常运行出你想要的结果,但是fastjson就会给你一些惊喜(自己试一下吧)。 为什么会有这种不同呢?
看看源码
一看源码便知。 首先json.org实现: public JSONObject put(String key, Object value) throws JSONException { if (key == null) { throw new NullPointerException("Null key."); } if (value != null) { testValidity(value); this.map.put(key, value); } else { this.remove(key); } return this; } 这里的put函数会将当前实例返回(return this).所以#2处的连续操作始终是当前实例出来的JSONObject的操作,是没有问题的。 再看fastjson中put实现方法: public Object put(String key, Object value) { return map.put(key, value); } 这里返回了map的put方法返回值,下面给出map的put方法实现:
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* [@param](https://my.oschina.net/u/2303379) key key with which the specified value is to be associated
* [@param](https://my.oschina.net/u/2303379) value value to be associated with the specified key
* [@return](https://my.oschina.net/u/556800) the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
当传入的key已经存在时,将返回key对应已有的value,如果key不存在,就会返回null,注释里面说的非常清楚。
总结
所以fastjson中的put会依据map中已有的key值来返回不同的值,所以#2中的toString是对key对应的值的操作,但是如果之前key在json中不存在就会变成对null的操作。 一点学习经历,不足之处,请多指正。