Fastjson反序列化泛型類型時候的一個問題


Java代碼   收藏代碼
  1. import static org.junit.Assert.assertFalse;  
  2. import static org.junit.Assert.assertTrue;  
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.junit.Test;  
  8.   
  9. import com.alibaba.fastjson.JSON;  
  10. import com.alibaba.fastjson.JSONArray;  
  11. import com.alibaba.fastjson.TypeReference;  
  12.   
  13. public class GenericTypeTest {  
  14.   
  15.     static class Foo<T>{  
  16.         private T t;  
  17.   
  18.         public T getT() {  
  19.             return t;  
  20.         }  
  21.   
  22.         public void setT(T t) {  
  23.             this.t = t;  
  24.         }  
  25.           
  26.     }  
  27.     @Test  
  28.     public void test_FirstWithClass() {  
  29.         Foo<List<Integer>> foo = new Foo<List<Integer>>();  
  30.         List<Integer> list = new ArrayList<Integer>();  
  31.         list.add(3);  
  32.         foo.setT(list);  
  33.         String v = JSON.toJSONString(foo);  
  34.         System.out.println(v);  
  35.         //parse with class  
  36.         Foo<?> rst = JSON.parseObject(v, foo.getClass());  
  37.         assertTrue(rst.getT() instanceof JSONArray);  
  38.         //parse with TypeReference  
  39.         rst = JSON.parseObject(v,new TypeReference<Foo<List<Integer>>>(){});  
  40.         assertTrue(rst.getT() instanceof JSONArray);//這里沒有失敗  
  41.     }  
  42. //  @Test//此用例跟上邊那個不能同時跑,要不然上邊跑過之后下邊就跑不通了  
  43.     public void test_FirstWithTypeReference() {  
  44.         Foo<List<Integer>> foo = new Foo<List<Integer>>();  
  45.         List<Integer> list = new ArrayList<Integer>();  
  46.         list.add(3);  
  47.         foo.setT(list);  
  48.         String v = JSON.toJSONString(foo);  
  49.         System.out.println(v);  
  50.         //parse with TypeReference  
  51.         Foo<?> rst = JSON.parseObject(v,new TypeReference<Foo<List<Integer>>>(){});  
  52.         assertFalse(rst.getT() instanceof JSONArray);   
  53.     }  
  54. }  

      文字描述的話就是:

Java代碼   收藏代碼
  1. 泛型類型反序列化調用paseObject的時候,第一次parseObject傳Class,后邊傳TypeReference或者Type就解析不出泛型類型了,泛型對應的類型只能解析成JsonObject  

      版本1.2.4及以前,可以解析泛型的版本,應該都有。暫時可以通過含泛型的對象反序列化的時候,只通過傳入Type或者TypeReference類型來實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM