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 = "[{
" + 
				"	"checkItemsId": "1",
" + 
				"	"checkItemsName": "aaaaaa1",
" + 
				"	"checkPosition": "aaaaaa"
" + 
				"}, {
" + 
				"	"checkItemsId": "2",
" + 
				"	"checkItemsName": "bbbbbbb1",
" + 
				"	"checkPosition": "bbbbbbb"
" + 
				"}, {
" + 
				"	"checkItemsId": "3",
" + 
				"	"checkItemsName": "ccccccc1",
" + 
				"	"checkPosition": "ccccccc"
" + 
				"}, {
" + 
				"	"checkItemsId": "4",
" + 
				"	"checkItemsName": "dddddddddd1",
" + 
				"	"checkPosition": "dddddddddd"
" + 
				"}, {
" + 
				"	"checkItemsId": "5",
" + 
				"	"checkItemsName": "eeeeeeeeee1",
" + 
				"	"checkPosition": "eeeeeeeeee"
" + 
				"}, {
" + 
				"	"checkItemsId": "6",
" + 
				"	"checkItemsName": "ffffffff1",
" + 
				"	"checkPosition": "ffffffff"
" + 
				"}]
" + 
				"";
		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); 
	}

}
原文地址:https://www.cnblogs.com/jimmyshan-study/p/11706364.html