• 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类型来实现。

  • 相关阅读:
    Linux下进程间通信的六种机制详解
    Android HAL实例解析
    socket函数
    Linux 线程浅析
    Android WiFi开发教程(一)——WiFi热点的创建与关闭
    Android蓝牙开发教程(三)——蓝牙设备相互通讯
    python数据分析入门学习笔记儿
    Oracle触发器详解
    电商检索系统总结——功能篇
    Linux内核中等待队列的几种用法
  • 原文地址:https://www.cnblogs.com/exmyth/p/5199525.html
Copyright © 2020-2023  润新知