Jackson將json字符串轉換成泛型List

Jackson,我感覺是在Java與Json之間相互轉換的最快速的框架,當然Google的Gson也很不錯,但是參照網上有人的性能測試,看起來還是Jackson比較快一點

    Jackson處理一般的JavaBean和Json之間的轉換只要使用ObjectMapper 對象的readValue和writeValueAsString兩個方法就能實現。但是如果要轉換複雜類型Collection如 List<YourBean>,那麼就需要先反序列化複雜類型 爲泛型的Collection Type。

如果是ArrayList<YourBean>那麼使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);

如果是HashMap<String,YourBean>那麼 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);

 

實例:

<pre name="code" class="java">import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Cesi {

	public static void main(String[] args) throws Exception {
		ObjectMapper obMapper2 = new ObjectMapper();
		Map<String, Object> mapText2 = new HashMap<String, Object>();
		List dataList2 = new ArrayList();
		
		//pojo類
		TextEntity entyti2 = new TextEntity();
		entyti2.setNum(122);
		entyti2.setRed("豔紅色的22");
		entyti2.setGreen("淡綠色的22");
		
		dataList2.add(entyti2);
		mapText2.put("textEntity", dataList2);
		
		ArrayList<TextEntity> dataListentity =  (ArrayList<TextEntity>) mapText2.get("textEntity");
		String json2 = obMapper2.writeValueAsString(dataListentity);
		System.out.println("dataListentity  json2="+json2);
		
		List<TextEntity> text2 = getslist(json2,TextEntity.class);
		System.out.println("EntityList2="+text2.get(0).getGreen());

	}
	
	public static  <T> T  getlist(String str,Class<T> cl) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		T t = mapper.readValue(str, cl);
		return t;
	}
	
	public static  <T> List<T>  getslist(String str,Class<T> cl) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, cl);
		List<T> t = mapper.readValue(str, javaType);
		return t;
	}

}



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章