Gson反序列化不同类型的JSON(ANDROID)
我正在登录。如果数据正确,请返回以下内容:Gson反序列化不同类型的JSON(ANDROID),android,json,gson,deserialization,Android,Json,Gson,Deserialization,我正在登录。如果数据正确,请返回以下内容: { "a": 1, "b":2, "c":3 } { "status": false, "error": { .... etc } } 如果数据不正确,请返回以下内容: { "a": 1, "b":2, "c":3 } { "status": false, "error": { .... etc } } 我的模特该怎么做我正在使用GS
{
"a": 1,
"b":2,
"c":3
}
{
"status": false,
"error": {
.... etc
}
}
如果数据不正确,请返回以下内容:
{
"a": 1,
"b":2,
"c":3
}
{
"status": false,
"error": {
.... etc
}
}
我的模特该怎么做我正在使用GSON。
我的代码:
Gson gson = new Gson();
//As I can get two types of answers, as would my code?
//Model model = gson.fromJson(my_json, Model.class);
我建议你这样做:
if(responsecode==200){
Model model = gson.fromJson(my_json, Model.class);
}
else if (responsecode==error){
AnotherModel anothermodel = gson.fromJson(my_json, AnotherModel.class);
}
另一种方法是将所有可能的响应放在一个Pojo
类中,就像斯奎兹莫在评论中说的那样:
{
"a": 1,
"b":2,
"c":3,
"status": false,
"error": "wrong password"
}
将上面的json示例粘贴到此站点:
并生成您的
Pojo
类为什么不将所有可能的字段放入您的模型中,然后只需检查error
中的null
?