自定义JSON可序列化以用于不同类型的响应

时间:2018-08-26 11:33:46

标签: android json-deserialization

我所有API的服务器响应均采用以下格式:

$("document").ready(...

我为响应创建了一个类:

{
"code":200,
"status":"success",
"response": {/*different type of responses in all APIs*/}
}

{
"code":200,
"status":"success",
"response": [/*different type of responses in all APIs*/]
}

如何在响应变量中获得不同类型的响应?

1 个答案:

答案 0 :(得分:0)

对您的回复消息使用通用:

public class Response<T> {
    @SerializedName("code")
    int code;
    @SerializedName("status")
    String status;
    @SerializedName("response")
    T response;
}

您的响应以及相应的数据模型如下:

Response<List<DataModel>>, Response<DataModel>, etc...

与Gson转换:

Type type = new TypeToken<Response<T>>(){}.getType();
Response<T> response = new Gson().fromJson(json, type);
相关问题