Fastjson反序列化泛型类型时候的一个问题

2018-01-19  本文已影响0人  sherlock_6981

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

上一篇下一篇

猜你喜欢

热点阅读