1. 對(duì)于List<MyEntity>反序列化
由于jvm運(yùn)行時(shí)對(duì)泛型處理的問(wèn)題, java并不支持List<MyEntity>.class這樣來(lái)獲取class所以調(diào)用ObjectMapper.readValue(jsonStr, clazz)方法將無(wú)法實(shí)現(xiàn); 如果強(qiáng)行做如下調(diào)用:
ObjectMapper mapper = new ObjectMapper();
String jsonstr = "[{\"name\":\"name1\"},{\"name\":\"name2\"},{\"name\":\"name3\"}]";
List<MyObject> list = mapper.readValue(jsonStr, List.class);
System.out.println(list.get(0).getName());
將會(huì)在試圖讀取MyObject對(duì)象的方法時(shí)報(bào)運(yùn)行時(shí)錯(cuò)誤, 這是jvm運(yùn)行時(shí)對(duì)泛型容器處理的問(wèn)題. 實(shí)際上上面代碼反序列化得到的list是List<LinkedHashMap>;
2. 一種解決反序列化泛型容器問(wèn)題的封裝
反序列化提供兩種對(duì)外方法, 一種是Class, 一種是TypeReference,
使用的時(shí)候如果遇到(當(dāng)然其他類型也可以用這個(gè)方法只是太麻煩不是嗎)List<>只需:
List<JobEntity> list = JacksonUtil.json2BeanByType(jsonstr, new TypeReference<List<JobEntity>>() {});
package com.feng.util;
import com.feng.entity.JobEntity;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
/**
* @Auther: feng
* @Date: 2019/7/28 12:09
* @Description:
*/
public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper();
public static String bean2Json(Object obj) throws IOException {
return mapper.writeValueAsString(obj);
}
public static <T> T json2BeanByType(String jsonStr, TypeReference tr)
throws IOException {
return mapper.readValue(jsonStr, tr);
}
public static <T> T json2Bean(String jsonStr, Class<T> clazz)
throws IOException {
return mapper.readValue(jsonStr, clazz);
}