如何在 Retrofit 中使用 Gson Converter 解析关联数组?

ped*_*fsn 5 android json gson retrofit

我正在收到JSON来自 PHP 服务器的响应。在android中,我需要编写一个java模型(POJO)来用来解析Retrofit(用于http请求的Android库)中的响应。

JSON 结构:

{
  "calendar": {
    "2016-06-10": [
      {
        "time": "10h00m",
        "title": "PROVA P2",
        "description": "LP / RED / ED.FIS - 80 E 90",
        "color": "#990000"
      }
    ],
    "2016-06-11": [
      {
        "time": "10h00m",
        "title": "SIMULADO",
        "description": "LOREM PSIUM DOLOR LOREM",
        "color": "#009900"
      },
      {
        "time": "11h00m",
        "title": "CONSELHO DE CLASSE",
        "description": "LOREM PSIUM DOLOR",
        "color": "#009900"
      }
    ]
  },
  "error": false
}
Run Code Online (Sandbox Code Playgroud)

JSON是来自 PHP 服务器。我该如何使用Retrofit来处理它?

Cli*_*gts 6

要使用动态键进行解析,您的类中JSON需要一个。MapPOJO

将以下POJO类添加到您的项目中:

  1. CalendarResponse.java

    public class CalendarResponse {
      @SerializedName("calendar")
      Map<String, List<Entry>> entries;
    
      @SerializedName("error")
      private boolean error;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. Entry.java

    public class Entry {
      @SerializedName("time")
      private String time;
    
      @SerializedName("title")
      private String title;
    
      @SerializedName("description")
      private String description;
    
      @SerializedName("color")
      private String color;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用CalendarResponse端点改造接口中的类,请参阅下面的示例

    public interface CalendarService {
      @GET("<insert your own relative url>")
      Call<CalendarResponse> listCalendar();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 执行调用(同步)如下:

    Call<CalendarResponse> call = calendarService.listCalendar();
    CalendarResponse result = call.execute().body();
    
    Run Code Online (Sandbox Code Playgroud)

如果需要,这里是一个解析JSONwith的示例GSON

Gson gson = new GsonBuilder().create();
CalendarResponse b = gson.fromJson(json, CalendarResponse.class);
Run Code Online (Sandbox Code Playgroud)


Cri*_*tan 0

通常,您会创建一个 POJO 来表示 JSON,但在本例中,您需要一个 2016-06-10 类和一个 2016-06-11 类。

这不是一个解决方案。因此,更改 JSON 响应以使日期成为单独的值:

{
  "calendar": [
    {
      "date": "2016-06-10",
      "entries": [
        {
          "time": "10h00m",
          "title": "PROVA P2",
          "description": "LP / RED / ED.FIS - 80 E 90",
          "color": "#990000"
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

更好的是,只需创建一个 dateTime 值并使其成为正确的ISO 8601时间戳即可:

{
  "calendar": [
      {
        "time": "2016-06-10T08:00:00.000Z",
        "title": "PROVA P2",
        "description": "LP / RED / ED.FIS - 80 E 90",
        "color": "#990000"
      }
    ]
}
Run Code Online (Sandbox Code Playgroud)

如果您无法控制提供 JSON 的服务器,那么您应该使用 Retrofit 来获取 String 并通过 gson 自行进行 Gson 转换。