天天看點

JSONObject序列化包含Date類型資料的Java對象

問題場景

在Java裡面,會遇到這樣的問題:資料庫中存在TIMESTAMP類型的資料,這樣Bean對象裡面就會有Date(java.util.Date)類型參數,我們使用JSONObject将對象序列化的時候,會發現Date屬性被分隔成年、月、日、時、分、秒等子對象了,這肯定不符合我們的期望。

解決方案

使用json-lib包提供的JsonConfig可以在處理Java對象和Json互轉時過濾屬性值,具體的方案如下:

  • 建立日期處理器類

利用SimpleDateFormat将Date類型的資料format一下,該類實作了JsonValueProcessor接口。

public class JsonDateValueProcessor implements JsonValueProcessor {

    private String format = "yyyy-MM-dd HH:mm:ss";

    public JsonDateValueProcessor() {
        super();
    }

    public JsonDateValueProcessor(String format) { // 自己需要的格式
        super();
        this.format = format;
    }

    @Override
    public Object processArrayValue(Object value, JsonConfig paramJsonConfig) {
        return process(value);
    }

    @Override
    public Object processObjectValue(String key, Object value, JsonConfig paramJsonConfig) {
        return process(value);
    }

    private Object process(Object value) {
        if (value instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
            return sdf.format(value);
        }
        return value == null ? "" : value.toString();
    }
}      
  • 使用方式

處理單個bean

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONObject json = new JSONObject();  
json.fromObject(object, jsonConfig)      
List<Object> objects = new ArrayList<>();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONArray taskArray = JSONArray.fromObject(objects, jsonConfig);      
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONObject json = new JSONObject();
json.putAll(Map, jsonConfig);