Jackson will turn json array generic List

Much gossip that directly on the work, see the code to understand.

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); 
	}

}

 

Guess you like

Origin www.cnblogs.com/jimmyshan-study/p/11706364.html