完美解决fastJson泛型多层级嵌套,类型转化错误
先把实体类上了再说:
import lombok.Data;
@Data
public class Man {
private String name;
private String pass;
public Man(String name, String pass) {
this.name = name;
this.pass = pass;
}
}
然后把result结果封装类上了:
import lombok.Data;
/**
* @author yangwulang
*/
@Data
public class Results<T> {
private T data;
}
注意:我们一般会这样解析json数据
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
/**
* @author yangwulang
*/
public class Pp {
public Results call(String jsons) {
TypeReference<Results<Man>> typeReference = new TypeReference<Results<Man>>(s()) {
};
return JSON.parseObject(jsons, typeReference);
}
}
但是写多了,就觉得很厌烦,然后会采用泛型,问题就来了
我一般会这么写
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
/**
* @author yangwulang
*/
public class Pp<T> {
public Results<T> call(String jsons) {
TypeReference<Results<T>> typeReference = new TypeReference<Results<T>>() {
};
return JSON.parseObject(jsons, typeReference);
}
}
然后就这么运行