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