java对象中含有Integer类型字段转json字符串问题


问题:对于含有Integer类型字段的java对象,在通过下面这种方式转为json字符串时,Integer类型的字段如果为空的情况下,会默认转化为0,但是我想让它为空的时候直接转化为null,不要默认为0.

String json = JSONObject.fromObject(bean).toString();

 

解决:可以自定义一下JsonConfig。

 

JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerDefaultValueProcessor(Integer.class, //定义Integer为null时   转为json 还是null,如果不自己定义的话,会默认返回0
                new DefaultValueProcessor(){
                    public Object getDefaultValue(Class type) {
                        return null;
                    }
        });
String json = JSONObject.fromObject(registerVO,jsonConfig).toString();

 

 

在项目中JsonConfig用的比较多的地方是需要重新定义Date类型数据的转换策略,JsonConfig配置如下:

public static JsonConfig getJsonConfig(String dateFormat) {
        JsonDateValueProcessor beanProcessor = new JsonDateValueProcessor();
        if (dateFormat != null) {
            DateFormat df = new SimpleDateFormat(dateFormat);
            beanProcessor.setDateFormat(df);
        }

        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
        return jsonConfig;
    }

 

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM