微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android json返回集合

Android开发中,使用JSON作为数据传输格式已经变得非常普遍。在一些接口请求中,我们可能需要返回一个集合类型(如List或Array)的数据,本文将介绍如何在Android中解析JSON返回的集合类型数据。

android json返回集合

首先,请求接口获取到的JSON数据可能长这样:

{

  "status": "0","message": "success","data": [

    {

      "id": "1","name": "张三","age": "18"

    },{

      "id": "2","name": "李四","age": "20"

    }

  ]

}

其中data字段是一个数组,包含了多个对象。我们可以使用Android自带的JSONObject和JSONArray类来解析这个JSON数据。下面是示例代码

String jsonString = response.body().string();

JSONObject jsonObject = new JSONObject(jsonString);

int status = jsonObject.getInt("status");

String message = jsonObject.getString("message");

JSONArray dataArray = jsonObject.getJSONArray("data");

List<Person> personList = new ArrayList<>();

for (int i = 0; i < dataArray.length(); i++) {

    JSONObject personObject = dataArray.getJSONObject(i);

    int id = personObject.getInt("id");

    String name = personObject.getString("name");

    int age = personObject.getInt("age");

    Person person = new Person(id,name,age);

    personList.add(person);

}

这段代码首先将JSON字符串转换为JSONObject对象,然后通过get方法获取status、message和dataArray字段的值。接着,我们循环遍历dataArray,将每个JSONObject对象转换为Person对象,并添加到personList中。

最后,我们就可以在Android应用中得到一个包含多个Person对象的List集合,可以根据需求进行处理和展示。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐