最近用到了json字符串轉實體類,轉集合的功能,
主要代碼如下:
/**
* json 字符串轉集合
*
* @author lipw
* @date 2017年5月10日下午6:08:17
* @param jsonString
* @param pojoCalss
* 集合中的類
* @return
*/
public static <T> List<T> jsonToList(String jsonString, Class<T> pojoCalss) {
if (jsonString.indexOf("%5B") != -1){
try {
jsonString = URLDecoder.decode(jsonString, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (StringUtil.isBlank(jsonString)) {
return null;
}
try {
String[] dateFormats = new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"};
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpherEx(dateFormats, null, null, false));
//JSONUtils.getMorpherRegistry().registerMorpher(morpher);
JSONArray jsonArray = JSONArray.fromObject(jsonString);
// Java集合
@SuppressWarnings("unchecked")
List<T> list = (List<T>) JSONArray.toCollection(jsonArray, pojoCalss);
return list;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
注意,這已經是修改完的代碼。
問題描述
1、當不添加以下代碼的時候,總是把日期轉換爲當前時間:
String[] dateFormats = new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"};
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpherEx(dateFormats, null, null, false));
這裏的 DateMorpherEx 是自己重寫的擴展類,如果你僅僅是解決此問題,可以改爲:DateMorpher,但是不能像我這樣使用4個參數的構造函數,因爲 DateMorpher 的 defaultValue 是不能爲 null 的。
2、添加以上代碼後,如果json字符串中的日期與dateFormats中的第一個不一致,就有可能產生一個問題:轉換出來的日期少了一年,月分也對不上。比如json字符串中的日期格式是:2019-04-04,而dateFormats中的第一個是yyyyMMdd,那就會出問題。
3、不允許傳空字符串值,否則出異常:Error while setting property=beginDate type class java.lang.String
這需要通過重寫 DateMorpher 類來實現。