Jackson 将数组json转List泛型

Posted JimmyShan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); 
	}

}

 

以上是关于Jackson 将数组json转List泛型的主要内容,如果未能解决你的问题,请参考以下文章

Jackson将json字符串转换成泛型List

Jackson将json字符串转换成泛型List

Jackson反序列化泛型List(使用JavaType将json字符串转换成泛型List)

jackson简单使用,对象转json,json转对象,json转list

jackson简单使用,对象转json,json转对象,json转list

如何将字符串转换成javaBean