alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.75k stars 6.5k forks source link

带泛型的对象不能被反序列化 #732

Open fixboom opened 8 years ago

fixboom commented 8 years ago

版本:fastjson-1.2.14 ` import java.io.Serializable;

import com.alibaba.fastjson.JSONObject;

public class Test {

public static void main(String[] args) {
    A a = new A();
    a.setMedia(new B<String>("hello"));

    JSONObject json = (JSONObject) JSONObject.toJSON(a);
    System.out.println(json.toJSONString());
    System.out.println(json.toJavaObject(A.class));
}

public static class A implements Serializable {
    private static final long serialVersionUID = 2377905273766145971L;
    private B<String> media;

    public B<String> getMedia() {
        return media;
    }

    public void setMedia(B<String> media) {
        this.media = media;
    }

}

public static class B<T> implements Serializable {
    private static final long serialVersionUID = 7265170200113094273L;
    private T content;

    public B(T t) { 
        this.content = t;
    }

    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

}

} `

报错:

Exception in thread "main" com.alibaba.fastjson.JSONException: can not cast to : Test.Test$B at com.alibaba.fastjson.util.TypeUtils.castToJavaBean(TypeUtils.java:921) at com.alibaba.fastjson.util.TypeUtils.cast(TypeUtils.java:615)

mykite commented 8 years ago

可以使用TypeReference

wenshao commented 8 years ago

https://github.com/alibaba/fastjson/wiki/TypeReference