用fastjson反序列化 带泛型的类

今天使用 fastjson 反序列化  泛型的类时,eclipse 一直提示编译错误!!



代码如下

public class Student {
	private int id;
	private String name;
	private T  course;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public T getCourse() {
		return course;
	}
	public void setCourse(T course) {
		this.course = course;
	}
	
}

    public void test1(){
        String json="{\"id\":\"1\",\"name\":\"李四\",\"course\":\"数学\"}";
        JSON.parseObject(json, Student.class);//一直报Student cannot be resolved to a variable
    }



后来发现查了资料,针对泛型类应该这么用:
List list = JSON.parseObject("...", new TypeReference<List>() {});

于是改成这样就OK了:

	public void test1(){
		String json="{\"id\":\"1\",\"name\":\"李四\",\"course\":\"数学\"}";
		JSON.parseObject(json, new TypeReference>(){});// 成功,不再提示编译错误
	}




你可能感兴趣的:(Java开发)