JSON 时间等常用转化的思路

问题
1.net.sf.json.JSONObject的formObject方法在转化时调到非lang和util的类的对象方法时,有时会报错
2.javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse:
    net.sf.json.JSONException: java.lang.reflect.InvocationTargetException


解决思路
1.分析错误的原因和地方
2.找到相应的转化问题所在
3.定义自己的JsonConfig


response.setCharacterEncoding("UTF-8");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd"));
jsonConfig.registerJsonValueProcessor(Time.class, new JsonTimeValueProcessor());
response.getWriter().write(JSONObject.fromObject(returnObject, jsonConfig).toString());


源码
附JsonDateValueProcessor源码

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

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

}


附JsonTimeValueProcessor源码

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Locale;

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

public class JsonTimeValueProcessor implements JsonValueProcessor {
	private String format = "HH:mm:ss";

	public JsonTimeValueProcessor() {
		super();
	}

	public JsonTimeValueProcessor(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 Time) {
			SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
			return sdf.format(value);
		}
		return value == null ? "" : value.toString();
	}

}



你可能感兴趣的:(json,JsonConfig,时间格式化)