1. 程式人生 > >專案____ajax,JSONArray,資料轉換異常

專案____ajax,JSONArray,資料轉換異常

json資料轉換異常:net.sf.json.JSONException: java.lang.reflect.InvocationTargetException

執行:
JSONArray array = JSONArray.fromObject(this.users);

就會報以下錯誤:
net.sf.json.JSONException: java.lang.reflect.InvocationTargetException

users是一個list集合

錯誤原因:資料庫中dltime欄位型別位date,向JSONArray轉換時出錯

方案一:

JSONArray array = JSONArray.fromObject(this.users.toArray());

專案中沒有.toArray()的也都正常運行了。這次異常中此方法沒有解決問題。

方案二:

因為bean裡有Date欄位,且從資料庫裡讀出來的是java.sql.Date,賦值給了java.util.Date,轉化成JSONArray時出錯;可以在從資料庫讀出Date 時直接寫成:new java.util.Date(rs.getDate("date").getTime),這樣就不會出錯了;

!!就是將出錯的資料讀出來轉成可以正常轉換的資料型別 如util.date或者string然後再轉成JSON

方案三:沒懂

日期格式hibernate延時載入

1.解決:日期格式

private java.util.Date createTime; 

只在欄位前宣告Date的資料型別可能也會拋異常,在Set,get方法中,有出現Date型別的都把包名加上

2.解決:hibernate延時載入 設定

Java程式碼  JsonConfig cfg = new JsonConfig(); cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});

方法舉例

Java程式碼 收藏程式碼
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.transaction.annotation.Transactional;

import com.csValue.common.util.DateJsonValueProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

public class test {

	@Transactional(readOnly = true)
	public JSONArray datagrid(Pager page, User user,
			DetachedCriteria detachedCriteria) {
		// 有級聯,不能直接轉化,要取出List放到map裡面
		JsonConfig cfg = new JsonConfig();

		// 過濾關聯,避免死迴圈net.sf.json.JSONException:
		// java.lang.reflect.InvocationTargetException
		cfg.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				if (name.equals("addressGroup") || name.equals("user")
						|| name.equals("createTime") || name.equals("birthday")) {
					return true;
				} else {
					return false;
				}
			}
		});
		// net.sf.json.JSONException:
		// java.lang.reflect.InvocationTargetException異常
		cfg.setExcludes(new String[] { "handler", "hibernateLazyInitializer" });
		// javabean裡出現迴圈呼叫啦,趕快用excludes幹掉parent或者children
		cfg.setExcludes(new String[] { "addressGroup" });
		// net.sf.json.JSONException:
		// java.lang.reflect.InvocationTargetException日期格式轉化出錯
		cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(
				"yyyy-MM-dd hh:mm:ss"));
		Pager pager = this.findAllByApprove(page, user, detachedCriteria);
		long total = pager.getTotalCount();
		List list = pager.getResult();
		Map result = new HashMap();
		result.put("total", total);
		result.put("rows", list);
		JSONArray jsonArray = JSONArray.fromObject(result, cfg);
		return jsonArray;
	}

}