【问题标题】:Retrieve data from json resource with Retrofit2使用 Retrofit2 从 json 资源中检索数据
【发布时间】:2019-06-12 04:25:20
【问题描述】:

我想用 Retrofit 制作 item POJO 类。我的 json 资源令人困惑,它有很多项目细节。我该怎么做?

{
"date" : "17-01-19",
"items": [
    {
        "id" : "123456789",
        "name" : "USA",
        "images": {
            "small": "https://www.google.com",
            "large": "https://www.google.com"
        }
    },
    {
        "id" : "123456789",
        "name" : "Finland",
        "images": {
            "small": "https://www.google.com",
            "large": "https://www.google.com"
        }
    },
    {
        "id" : "123456789",
        "name" : "Germany",
        "images": {
            "small": "https://www.google.com",
            "large": "https://www.google.com"
        }
    }

]

}

【问题讨论】:

标签: android json rest retrofit retrofit2


【解决方案1】:
package com.example;

import com.google.gson.annotations.SerializedName;

public class Images {

@SerializedName("small")
public String small;
@SerializedName("large")
public String large;

}


package com.example;

import com.google.gson.annotations.SerializedName;

public class Item {

@SerializedName("id")
public String id;
@SerializedName("name")
public String name;
@SerializedName("images")
public Images images;

}



package com.example;

import java.util.List;
import com.google.gson.annotations.SerializedName;

public class Response {

@SerializedName("date")
public String date;
@SerializedName("items")
public List<Item> items = null;

}

或插入public Images images;,您可以使用public Map&lt;String,String&gt; images;

【讨论】:

    【解决方案2】:

    创建 POJO 的一种快速且自动化的方法是使用 Android Studio 插件。这是我以前用过的一个:

    https://plugins.jetbrains.com/plugin/8533-json2pojo

    您基本上将您的 JSON 复制并粘贴到插件中,它会自动为您生成 POJO。在大多数情况下,您可以按原样使用它,也可以进一步调整它。

    另一个选择是这个网站:

    http://www.jsonschema2pojo.org/

    此类工具对更复杂的 API 非常有用。有时它们不是 100% 正确或需要稍作调整,但它们确实完成了大部分工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多