http://yueyemaitian.iteye.com/blog/2178095
Java代碼?
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{??
private?T?t;??
public?T?getT()?{??
return?t;??
????????}??
public?void?setT(T?t)?{??
this.t?=?t;??
????????}??
????}??
@Test??
public?void?test_FirstWithClass()?{??
Foo>?foo?=new?Foo>();??
List?list?=new?ArrayList();??
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>>(){});??
assertTrue(rst.getT()instanceof?JSONArray);//這里沒有失敗??
????}??
//??@Test//此用例跟上邊那個不能同時跑,要不然上邊跑過之后下邊就跑不通了??
public?void?test_FirstWithTypeReference()?{??
Foo>?foo?=new?Foo>();??
List?list?=new?ArrayList();??
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>>(){});??
assertFalse(rst.getT()instanceof?JSONArray);???
????}??
}??
? ? ? 文字描述的話就是:
Java代碼?
泛型類型反序列化調用paseObject的時候,第一次parseObject傳Class,后邊傳TypeReference或者Type就解析不出泛型類型了,泛型對應的類型只能解析成JsonObject??
?? ? ?版本1.2.4及以前,可以解析泛型的版本,應該都有。暫時可以通過含泛型的對象反序列化的時候,只通過傳入Type或者TypeReference類型來實現。