NullPointerException on ToString()
Brought to you by:
aalmiray
An NPE is fired when trying to create an JSONObject and using put to add an element and directly after that using a toString().
new JSONObject().put("success", "true").toString();
I think the returned previous - Object of method put is after a new initalizied JSONObject a null object.
version 2.4
Workaround:
JSONObject jsonObj = new JSONObject();
jsonObj.put("success", "true");
jsonObj.toString();
Bug :
public Object put( Object key, Object value ) {
if( key == null ){
throw new IllegalArgumentException( "key is null." );
}
Object previous = properties.get( key ); *** // IF new initalized map , get returns null! which is also returned by this put method! ***
element( String.valueOf( key ), value );
return previous;
}
But aren't Map.put implementations are supposed to do that? https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#put(K,%20V)
Yes , i dont say that the map implementation is wrong, i mean the put operation of JSONObject is wrong. :)
You see in the lib source documentation : http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html is mentioned that it is possible to do this:
The put methods adds values to an object. For example,
produces the string {"JSON": "Hello, World"}.
But that can't work with the put implementation of JSONObject.
JSONObject implements Map, right?
http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html#put(java.lang.Object, java.lang.Object)
I would agree the text at the top of the JavaDoc, under "The put methods adds values to an object. For example," is misleading as it suggest put returns the value that's been put. In fact it should return the previous value, or null if there wasn't one already. Map.put documents this as:
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)
I think the problem is in the JavaDoc for JSONObject.
I didn't see your last comment before I posted. I think we're agreeing!
ok :D
Development of this library has been moved to GitHub since 2010, please report any issues you may find at https://github.com/kordamp/json-lib/issues