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