时间Date格式转换为json后出现的问题处理

在date形数据转换成json后或出现如下情况:

[{"CreateTime":{"date":4,"day":0,"hours":23,"minutes":58,"month":5,"seconds":9,"time":1496591889969,"timezoneOffset":-480,"year":117},"userName":"Woods"}]

这样前端不好处理

处理方法:

package com.couponMgmt.core.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import net.sf.json.JsonConfig;
import net.sf.json.processors.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;  
    }  

    public Object processArrayValue(Object paramObject, JsonConfig paramJsonConfig) {  
        return process(paramObject);  
    }  

    public Object processObjectValue(String paramString, Object paramObject,  JsonConfig paramJsonConfig) {  
        return process(paramObject);  
    }  

    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();    
    }  
}


测试一下

package couponMgmt;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.couponMgmt.core.utils.JsonDateValueProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

public class JSONTEST {

    public static void main(String[] args) {

        List list = new ArrayList<>();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("Woods");
        userInfo.setEnrollTime(new Date());
        list.add(userInfo);
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        JSONArray jsonArray2 = JSONArray.fromObject(list, config);
        System.out.println(jsonArray2);
    }

}


返回结果:


[
    {
        "enrollTime": "2017-06-05 00:00:12",
        "userName": "Woods"
    }
]

你可能感兴趣的:(问题)