【问题标题】:Gson deserialize JSON different types (ANDROID)Gson 反序列化不同类型的 JSON (ANDROID)
【发布时间】:2016-05-18 19:31:04
【问题描述】:

我正在登录。如果数据正确,则返回以下内容:

{
   "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);

【问题讨论】:

  • 为什么不将所有可能的字段放入模型中,然后检查error 是否有null

标签: android json gson deserialization


【解决方案1】:

我建议你这样:

if(responsecode==200){
   Model model = gson.fromJson(my_json, Model.class);
}
else if (responsecode==error){
   AnotherModel anothermodel = gson.fromJson(my_json, AnotherModel.class);
}

另一种方法是将所有可能的响应放在一个 Pojo 类中,就像 SqueezyMo 在 cmets 中所说:

{
  "a": 1,
  "b":2,
  "c":3,
  "status": false,
  "error": "wrong password"
}

将上面的 json 示例粘贴到该站点:Json Schema 2 Pojo 并生成你的Pojo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多