使用 Retrofit 解析包含具有不同属性的对象的 JSON 数组 [英] Parsing JSON array that contain objects with different attributes with Retrofit

查看:87
本文介绍了使用 Retrofit 解析包含具有不同属性的对象的 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解析包含没有名称的 JSON 对象的 JSON 数组,并且每个对象在带有 Retrofit2 的 Android 中都有自己的属性.Json 是这样的:

<预><代码>[{"用户名":"alexruskovski",年龄":27,活动":真},{"语言":"Java","职业":"编程","phone_num":"123456789","电子邮件":"asdf@qwe.com"}]

我的 POJO 是这样的:

用户:

 公共类用户{字符串用户名;年龄;布尔活动;}

这里是数据对象:

公共类数据{字符串语言,字符串占用;字符串电话号码;字符串电子邮件;}

这是我的主要响应类:

公共类 MainResponse{用户用户;数据数据;}

这就是我的 Retrofit 客户端 getData 方法

Call>获取数据();

解决方案

要解析该响应,您需要以下类

 公共类 MainResponse{字符串用户名;年龄;布尔活动;字符串语言;字符串占用;字符串电话号码;字符串电子邮件;}

还有你的 getData 方法

Call>获取数据();

how can I parse JSON array that contains JSON objects without names and each object have his own attributes in Android with Retrofit2. Json is something like this:

[
{
    "username":"alexruskovski",
    "age":27,
    "active":true
},
{
    "languages":"Java",
    "occupation":"Programming",
    "phone_num":"123456789",
    "email":"asdf@qwe.com"
}
]

And I have my POJO's like this:

user:

   public class User{
      String username;
      int age;
      boolean active;
   }

and here is the data object:

public class Data{
   String languages,
   String occupation;
   String phone_num;
   String email;
}

and this is my main response class:

public class MainResponse{
   User user;
   Data data;
}   

And this is how my Retrofit client getData method is

Call<List<MainResponse>> getData();

解决方案

To parse that response you need the following class

  public class MainResponse{
    String username;
    int age;
    boolean active;
    String languages;
    String occupation;
    String phone_num;
    String email;
}

And your getData method

Call<List<MainResponse>> getData();

这篇关于使用 Retrofit 解析包含具有不同属性的对象的 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆