您的位置:首页 > 移动开发 > Objective-C

JSON通过配置文件格式化时间属性(解决[object Object]问题)

2015-09-02 11:20 686 查看
前段时间项目实战,遇到一个问题,后台通过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格式的时间就可以在前台页面进行格式化输出了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: