为什么这不可能?
Type type = newResponse.getDataType().getType();
Class<?> tClass = type.getClass();
Type arrayType = new TypeToken<ArrayList<tClass>>(){}.getType();
完整的解串器如下 -
public class NewJsonDesrializer implements JsonDeserializer<NewResponse> {
@Override
public NewResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonElement = json.getAsJsonObject();
NewResponse newResponse = new Gson().fromJson(json, typeOfT);
JsonElement data = jsonElement.get("data");
if(data.isJsonArray()){
Type type = newResponse.getDataType().getType();
Class<?> tClass = type.getClass();
Type arrayType = new TypeToken<ArrayList<tClass>>(){}.getType();
newResponse.setData(new Gson().fromJson(data, arrayType));
}else{
newResponse.setData(new Gson().fromJson(data, newResponse.getDataType().getType()));
}
return newResponse;
}
}
这会在行 -
上面的反序列化器中抛出错误Error:(36, 54) error: cannot find symbol class tClass
完成NewResponse类如下 -
public class NewResponse<T> implements Serializable {
private boolean status;
private String message;
private T data;
private Constants.DataType dataType;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Constants.DataType getDataType() {
return dataType;
}
public void setDataType(Constants.DataType dataType) {
this.dataType = dataType;
}
}
返回Type
的枚举如下 -
public enum DataType{
@SerializedName("user")
USER(User.class);
Type type;
DataType(Type type) {
this.type = type;
}
public Type getType(){
return type;
}
}
Json结构如下 -
{
status:true,
message:"Registration Complete.",
dataType:"user",
data:[
{
username:"sachin@example.com",
email:"sachin@example.com",
created_on:"1426663448",
last_login:null,
active:"1",
first_name:"Sachin Gutte",
last_name:"",
company:null,
phone:null,
sign_up_mode:"GOOGLE_PLUS"
},
{
username:"administrator",
email:"admin@admin.com",
created_on:"1268889823",
last_login:"1425373557",
active:"1",
first_name:"Admin",
last_name:"istrator",
company:"ADMIN",
phone:"0",
sign_up_mode:"SOMEAPP"
}
]
}
答案 0 :(得分:1)
抱歉,我没有足够的声誉发表评论。
您必须通过编译时知道类型,而不是运行时。这就是为什么它无法解决。请看一下这个链接:http://docs.oracle.com/javase/tutorial/java/generics/erasure.html