問題:對於含有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; }