1. 程式人生 > >java,返回的json資料中Date型別格式的轉換

java,返回的json資料中Date型別格式的轉換

轉載自:http://blessht.iteye.com/blog/2018901

返回json資料時,資料庫中的Date型別是這種格式:"planTime":{"date":22,"day":6,"hours":0,"minutes":0,"month":3,"seconds":0,"time":1492790400000,"timezoneOffset":-480,"year":117}怎麼轉換成想要的yyyy-MM-dd格式呢?

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

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

/**
 * 時間轉換器(將返回的json資料中的日期格式轉換為指定格式)
 * Created by  on 2017/4/24.
 */
public class JsonDateValueProcessorUtil implements JsonValueProcessor {
    private String format ="yyyy-MM-dd";

    public JsonDateValueProcessorUtil() {
        super();
    }

    public JsonDateValueProcessorUtil(String format) {
        super();
        this.format = format;
    }

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

    @Override
    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();
    }
}
然後在轉換json資料的地方:
Flexigrid flexigrid = superviseService.queryPage(pageNumInt,pageSizeInt,supervise);                
List<Supervise> list = (List<Supervise>) flexigrid.getRows();                                      
int total = flexigrid.getTotal();                                                                  
int page = flexigrid.getPage();                                                                    
int rowStart = flexigrid.getRowStart();                                                            
int rowEnd = flexigrid.getRowEnd();                                                                
int rp = flexigrid.getRp();                                                                        
JsonConfig jsonConfig = new JsonConfig();                                                          
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessorUtil());               
JSONArray array = JSONArray.fromObject(list,jsonConfig);                                           

"planTime":"2017-04-22"


返回的日期格式就是我們指定的yyyy-MM-dd了。