import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.TypeReference; public class GenericTypeTest { static class Foo<T>{ private T t; public T getT() { return t; } public void setT(T t) { this.t = t; } } @Test public void test_FirstWithClass() { Foo<List<Integer>> foo = new Foo<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); list.add(3); foo.setT(list); String v = JSON.toJSONString(foo); System.out.println(v); //parse with class Foo<?> rst = JSON.parseObject(v, foo.getClass()); assertTrue(rst.getT() instanceof JSONArray); //parse with TypeReference rst = JSON.parseObject(v,new TypeReference<Foo<List<Integer>>>(){}); assertTrue(rst.getT() instanceof JSONArray);//这里没有失败 } // @Test//此用例跟上边那个不能同时跑,要不然上边跑过之后下边就跑不通了 public void test_FirstWithTypeReference() { Foo<List<Integer>> foo = new Foo<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); list.add(3); foo.setT(list); String v = JSON.toJSONString(foo); System.out.println(v); //parse with TypeReference Foo<?> rst = JSON.parseObject(v,new TypeReference<Foo<List<Integer>>>(){}); assertFalse(rst.getT() instanceof JSONArray); } }
文字描述的话就是:
泛型类型反序列化调用paseObject的时候,第一次parseObject传Class,后边传TypeReference或者Type就解析不出泛型类型了,泛型对应的类型只能解析成JsonObject
版本1.2.4及以前,可以解析泛型的版本,应该都有。暂时可以通过含泛型的对象反序列化的时候,只通过传入Type或者TypeReference类型来实现。