Menu

Conversion from null to empty string

Help
Macloud
2007-04-14
2013-04-29
  • Macloud

    Macloud - 2007-04-14

    Hi.
    I found such code in JSONObject.java:796

    ...}else if( String.class.isAssignableFrom( type ) || JSONUtils.isString( value ) ){
                String str = String.valueOf( value );
                if( value == null ){
                   setProperty( object, key, "", excludes, ignoreDefaultExcludes );
                }else...

    So, if type of value is String and value is null, then it is replaced with empty string. Was it desired? Values in arrays and maps are not converted in such way.

    So, the following code:

            Map m = new HashMap();
            m.put("a","A");
            m.put("b","B");
            m.put("C",null);
            JSONObject jmap = JSONObject.fromMap(m);
            System.out.println( jmap );

            MyBean obj = new MyBean();
            obj.setA("A");
            obj.setB("B");
            obj.setC(null);
            JSONObject jobj = JSONObject.fromObject(obj);
            System.out.println(jobj);

    produces different lines:

    {"a":"A","C":null,"b":"B"}
    {"a":"A","c":"","b":"B"}

     
    • aalmiray

      aalmiray - 2007-04-14

      Macloud,
      Per the json spec, a string can not be null, only objects. In your example I assume that property 'c' of MyBean is
      of type String, so the json oputput is correct. In the map example, you do not know in advance that the value associated
      with key 'c' should be treated as a String, so it gets treated as an null object, hence the null value in the resulting
      json.

      A quick test using generics on the map (Map<String,String>) will reveal that a null value will be treated as a null object
      instead of an empty String. There is no easy solution for now, without breaking backward compatibility on jdk1.3

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.