Jackson 將數組json轉List泛型


閑話不多說,直接上干活,見代碼就懂。

package com.zzcloud.job.common;

import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzcloud.job.common.entity.CheckItemsChild;

public class Test {

	public static void main(String[] args) throws Exception {
		String json = "[{\r\n" + 
				"	\"checkItemsId\": \"1\",\r\n" + 
				"	\"checkItemsName\": \"aaaaaa1\",\r\n" + 
				"	\"checkPosition\": \"aaaaaa\"\r\n" + 
				"}, {\r\n" + 
				"	\"checkItemsId\": \"2\",\r\n" + 
				"	\"checkItemsName\": \"bbbbbbb1\",\r\n" + 
				"	\"checkPosition\": \"bbbbbbb\"\r\n" + 
				"}, {\r\n" + 
				"	\"checkItemsId\": \"3\",\r\n" + 
				"	\"checkItemsName\": \"ccccccc1\",\r\n" + 
				"	\"checkPosition\": \"ccccccc\"\r\n" + 
				"}, {\r\n" + 
				"	\"checkItemsId\": \"4\",\r\n" + 
				"	\"checkItemsName\": \"dddddddddd1\",\r\n" + 
				"	\"checkPosition\": \"dddddddddd\"\r\n" + 
				"}, {\r\n" + 
				"	\"checkItemsId\": \"5\",\r\n" + 
				"	\"checkItemsName\": \"eeeeeeeeee1\",\r\n" + 
				"	\"checkPosition\": \"eeeeeeeeee\"\r\n" + 
				"}, {\r\n" + 
				"	\"checkItemsId\": \"6\",\r\n" + 
				"	\"checkItemsName\": \"ffffffff1\",\r\n" + 
				"	\"checkPosition\": \"ffffffff\"\r\n" + 
				"}]\r\n" + 
				"";
		ObjectMapper objMapper = new ObjectMapper();
		JavaType javaType = getCollectionType(ArrayList.class, CheckItemsChild.class); 
		List<CheckItemsChild> list = (List<CheckItemsChild>)objMapper.readValue(json, javaType );
		list.stream().forEach(p -> System.out.println(p.getCheckItemsName()));
		
	}
	
	public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { 
		ObjectMapper mapper = new ObjectMapper();
		return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); 
	}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM