修改JSONObject.fromObject数字为null时被转换为0

来源:互联网 发布:linux 用终端打开文件 编辑:程序博客网 时间:2024/06/06 01:15
如果未设置的话默认是DefaultDefaultValueProcessor 

Java代码  收藏代码
  1. public class DefaultDefaultValueProcessor implements DefaultValueProcessor {  
  2.    public Object getDefaultValue( Class type ) {  
  3.       if( JSONUtils.isArray( type ) ){  
  4.          return new JSONArray();  
  5.       }else if( JSONUtils.isNumber( type ) ){  
  6.          if( JSONUtils.isDouble( type ) ){  
  7.             return new Double( 0 );  
  8.          }else{  
  9.             return new Integer( 0 );  
  10.          }  
  11.       }else if( JSONUtils.isBoolean( type ) ){  
  12.          return Boolean.FALSE;  
  13.       }else if( JSONUtils.isString( type ) ){  
  14.          return "";  
  15.       }  
  16.       return JSONNull.getInstance();  
  17.    }  
  18. }  



在jsonConfig 注册defaultValueProcessor 

Java代码  收藏代码
  1. // 设置Integer类型为空的默认值 json-lib默认是0  
  2. jsonConfig.registerDefaultValueProcessor(Integer.class,  
  3.         new DefaultValueProcessor() {  
  4.             public Object getDefaultValue(Class type) {  
  5.                 return null;  
  6.             }  
  7.         });  


这样转换时Integer类型如果为null转换还是null,不会被转为0

转自:http://yaoba.iteye.com/blog/555806

0 0
原创粉丝点击