Android 自定义JSON可序列化不同类型的响应
“我的所有API”的服务器响应采用以下格式:Android 自定义JSON可序列化不同类型的响应,android,json-deserialization,Android,Json Deserialization,“我的所有API”的服务器响应采用以下格式: { "code":200, "status":"success", "response": {/*different type of responses in all APIs*/} } { "code":200, "status":"success", "response": [/*different type of responses in all APIs*/] } 我已经为响应创建了一个类: public class Response {
{
"code":200,
"status":"success",
"response": {/*different type of responses in all APIs*/}
}
{
"code":200,
"status":"success",
"response": [/*different type of responses in all APIs*/]
}
我已经为响应创建了一个类:
public class Response {
@SerializedName("code")
int code;
@SerializedName("status")
String status;
@SerializedName("response")
String response;
}
如何在响应变量中获得不同类型的响应?对响应消息使用generic:
public class Response<T> {
@SerializedName("code")
int code;
@SerializedName("status")
String status;
@SerializedName("response")
T response;
}
公共类响应{
@序列化名称(“代码”)
int代码;
@序列化名称(“状态”)
字符串状态;
@SerializedName(“响应”)
T反应;
}
您对相应数据模型的响应如下:
Response<List<DataModel>>, Response<DataModel>, etc...
响应、响应等。。。
使用Gson转换:
Type type = new TypeToken<Response<T>>(){}.getType();
Response<T> response = new Gson().fromJson(json, type);
Type Type=new-TypeToken(){}.getType();
Response-Response=new Gson().fromJson(json,类型);
但如何将Gson与之配合使用?