net.sf.json.JSONException: java.lang.reflect.InvocationTargetException

        json-lib将对象转化为json格式的数据时抛出net.sf.json.JSONException: va.lang.reflect.InvocationTargetException异常一般有两种情况:

        1、hibernate的延时加载

       解决方法:

       

JsonConfig jsonConfig = new JsonConfig();  
 
cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"}); 

      2、日期格式问题

      解决方法:

jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());

    JsonDateValueProcessor.java

    

package com.gdin.anta.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 {

	 /**
     * datePattern
     */
    private String datePattern = "yyyy-MM-dd";

    /**
     * JsonDateValueProcessor
     */
    public JsonDateValueProcessor() {
        super();
    }

    /**
     * @param format
     */
    public JsonDateValueProcessor(String format) {
        super();
        this.datePattern = format;
    }

    /**
     * @param value
     * @param jsonConfig
     * @return Object
     */
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);
    }

    /**
     * @param key
     * @param value
     * @param jsonConfig
     * @return Object
     */
    public Object processObjectValue(String key, Object value,
            JsonConfig jsonConfig) {
        return process(value);
    }

    /**
     * process
     * @param value
     * @return
     */
    private Object process(Object value) {
        try {
            if (value instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
                        Locale.UK);
                return sdf.format((Date) value);
            }
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            return "";
        }

    }

    /**
     * @return the datePattern
     */
    public String getDatePattern() {
        return datePattern;
    }

    /**
     * @param pDatePattern the datePattern to set
     */
    public void setDatePattern(String pDatePattern) {
        datePattern = pDatePattern;
    }


}

 

猜你喜欢

转载自freedomchx.iteye.com/blog/1835796