...}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 );
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
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
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"}
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