1. 程式人生 > >JSON通過配置檔案格式化時間屬性(解決[object Object]問題)

JSON通過配置檔案格式化時間屬性(解決[object Object]問題)

  前段時間專案實戰,遇到一個問題,後臺通過JSON轉變資料交換格式,然後在前臺輸出結果時,物件中的時間顯示竟然是[object Object],思考很久,查閱網上資料,才找到解決辦法:
		try {
				HttpSession session = request.getSession();
				
				Employee employee = (Employee)session.getAttribute("employee");
				int empId = employee.getEmpId();
				response.setContentType("text/html;charset=UTF-8");
				JsonConfig config = new JsonConfig();
				config.setIgnoreDefaultExcludes(false);
				config.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor("yyyy-MM-dd"));
				List<LeaveApplication> leaveApplicationList = leaveApplicationService.findByEmpId(empId);
				JSONArray resultArray = JSONArray.fromObject(leaveApplicationList,config);
				String lList = "{\"total\":"+leaveApplicationService.personalTotalSize(empId)+",\"rows\":"+resultArray+"}";
				PrintWriter out = response.getWriter();
				out.write(lList);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		
	
	

關鍵程式碼是:

JsonConfig config = new JsonConfig();
				config.setIgnoreDefaultExcludes(false);
				config.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor("yyyy-MM-dd"));
				List<LeaveApplication> leaveApplicationList = leaveApplicationService.findByEmpId(empId);
				JSONArray resultArray = JSONArray.fromObject(leaveApplicationList,config);
				String lList = "{\"total\":"+leaveApplicationService.personalTotalSize(empId)+",\"rows\":"+resultArray+"}";

JSON時間處理的工具類程式碼如下:
package com.ghost.util;

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";
	
	public JsonDateValueProcessor() {
		super();
	}
	
	public JsonDateValueProcessor(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格式的時間就可以在前臺頁面進行格式化輸出了