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

JAVA学习网 2018-12-28 13:34:01

问题:对于含有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;
    }

 

 

 


 

阅读(7191) 评论(0)