Why this is not possible ?
Type type = newResponse.getDataType().getType();
Class<?> tClass = type.getClass();
Type arrayType = new TypeToken<ArrayList<tClass>>(){}.getType();
Complete deserializer is as follows -
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;
}
}
This throws error in deserializer above at line -
Error:(36, 54) error: cannot find symbol class tClass
Complete NewResponse class is as follows-
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;
}
}
Enum that returns Type is as follows -
public enum DataType{
@SerializedName("user")
USER(User.class);
Type type;
DataType(Type type) {
this.type = type;
}
public Type getType(){
return type;
}
}
Json structure is as follows -
{
status:true,
message:"Registration Complete.",
dataType:"user",
data:[
{
username:"[email protected]",
email:"[email protected]",
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:"[email protected]",
created_on:"1268889823",
last_login:"1425373557",
active:"1",
first_name:"Admin",
last_name:"istrator",
company:"ADMIN",
phone:"0",
sign_up_mode:"SOMEAPP"
}
]
}
Type arrayType = new TypeToken<ArrayList<tClass>>(){}.getType();is a strange line.TypeTokendoesn't know what type of ArrayList it is parametrized with - this information isn't kept at runtime. And why are you creating an anonymous subtype of TypeToken and then calling thegetType()method? How would this be any different from not creating an anonymous subtype?