首页 > 解决方案 > 如何使用 Retrofit Api 解析 Json 对象列表

问题描述

{
    "0": {
        "id": "1",
        "img": "ginterests/1.png",
        "title": "Training & Educations",
        "description": "Yoga | Fitness | Daily Trainings | Dance | Music +",
        "follow": 1
    },
    "1": {
        "id": "2",
        "img": "ginterests/2.png",
        "title": "Consultations",
        "description": "Legal | Studies | Entrance Exam Preparations +",
        "follow": 1
    },
    "2": {
        "id": "3",
        "img": "ginterests/3.png",
        "title": "Public Events",
        "description": "City Events | Trending | Current Events +",
        "follow": 0
    },
    "3": {
        "id": "4",
        "img": "ginterests/4.png",
        "title": "Business Events",
        "description": "Talks & Shows | Press | Live coverage | Business meets +",
        "follow": 0
    },
    "4": {
        "id": "5",
        "img": "ginterests/5.png",
        "title": "Performances",
        "description": "Regional & Global | Celebreties | Standup +",
        "follow": 0
    },
    "5": {
        "id": "6",
        "img": "ginterests/6.png",
        "title": "News & Entertainment",
        "description": "Regional & Global | News | Trending +",
        "follow": 0
    },
    "6": {
        "id": "7",
        "img": "ginterests/default.png",
        "title": "Celebrities",
        "description": "City Events | Trending | Current Events +",
        "follow": 0
    },
    "success": true,
    "message": "Interests data sent",
    "interestsCount": 7
}

标签: androidjsonretrofit

解决方案


解析 JSON 对象并从中获取单个数据很容易。只需按照以下步骤操作:

  1. 将完整的响应存储为字符串值:final String response= response.body().string();
  2. 初始化一个 JSON 对象:JSONObject resultObject = null;
  3. 现在运行以下代码来解析 JSON 对象中的数据:`try {

                resultObject = new JSONObject(response);
                JSONObject result = resultObject.getJSONObject(0);
                final String id= volumeObject.getString("id"); //repeat this step to get all the data from the JSON object 
            } catch (JSONException e) {
                e.printStackTrace();
            }`
    

推荐阅读