JSONOBject中保存的Date值

JSONObject在装载Date类型数据时,会把一个Date按照既定的时间格式拆分,拼成一组json对,保存起来,格式如下:

{"id":"id","time":{"time":1403514899117,"minutes":14,"seconds":59,"hours":17,"month":5,"year":114,

"timezoneOffset":-480,"day":1,"date":23},"name":"ss"}。如果要保存为能看懂的时间值,只能通过把Date格式化为字符串后在保存,或者利用JsonValueProcessor的子类对象,把Date过滤成能看懂的一个时间了格式,如下:

 

1、创建一个JsonValueProcessor的实现类【JsonDateValueProcessor】

 

public class JsonDateValueProcessor implements JsonValueProcessor {

    private String dateFormate = "yyyy-MM-dd HH:mm:ss"; // default

    public JsonDateValueProcessor() {
    }

    public JsonDateValueProcessor(String dateFormate) {
        this.dateFormate = dateFormate;
    }

    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value, jsonConfig);
    }

    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        return process(value, jsonConfig);
    }

    private Object process(Object value, JsonConfig jsonConfig) {
        if (value instanceof Date) {
            String str = new SimpleDateFormat(dateFormate).format((Date) value);
            return str;
        }
        return value == null ? null : value.toString();
    }

}

 

2、创建一个普通的javaBean,省略。

3、通过JSONObject.fromObject(bean, JsonConfig)把javaBean转化成JsonObject

       

        Testd bean = new Testd();
        bean.setId("id");
        bean.setName("ss");
        bean.setTime(new Date());
        //结果1 没有利用JsonValueProcessor过滤
        JSONObject jo = JSONObject.fromObject(bean);
        System.out.println(jo.toString() + "======================");
       
       
        JsonConfig defaultJsonConfig = new ExtJsonConfig();
        defaultJsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
        defaultJsonConfig.registerJsonValueProcessor(BaseCustomEnum.class, new JsonCustomEnumEnumValueProcessor());
        defaultJsonConfig.setJavaPropertyFilter(new ExtPropertyFilter(defaultJsonConfig));

 

         // 结果2 利用JsonValueProcessor过滤
        JSONObject jo1 = JSONObject.fromObject(bean, defaultJsonConfig);
        System.out.println(jo1.toString() + "=======++++++===============");

 

打印出来的结果:

结果1:

{"id":"id","time":{"time":1403514899117,"minutes":14,"seconds":59,"hours":17,"month":5,"year":114,

"timezoneOffset":-480,"day":1,"date":23},"name":"ss"}======================

 

结果2:

{"id":"id","time":"2014-06-23 17:14:59","name":"ss"}=======++++++===============

所以,JSONObject中保存的Date应该需要格式化,要不保存后的值在程序中不好用。

 

你可能感兴趣的:(JSONObject)