Menu

#139 NullPointerException on ToString()

v1.0 (example)
open
nobody
None
5
2020-11-08
2016-06-02
Kami
No

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

Discussion

  • Kami

    Kami - 2016-06-02

    Workaround:
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("success", "true");
    jsonObj.toString();

     
  • Kami

    Kami - 2016-06-02

    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;
    }

     
  • Kami

    Kami - 2016-06-02

    Yes , i dont say that the map implementation is wrong, i mean the put operation of JSONObject is wrong. :)

     
  • Kami

    Kami - 2016-06-02

    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,

     myString = new JSONObject().put("JSON", "Hello, World!").toString();
    

    produces the string {"JSON": "Hello, World"}.

    But that can't work with the put implementation of JSONObject.

     
  • Jim Holmes

    Jim Holmes - 2016-06-02

    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.

     
  • Jim Holmes

    Jim Holmes - 2016-06-02

    I didn't see your last comment before I posted. I think we're agreeing!

     
  • Kami

    Kami - 2016-06-02

    ok :D

     
  • aalmiray

    aalmiray - 2020-11-08

    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

     

Log in to post a comment.