我从 PHP 服务器接收到 JSON
响应。在 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
}
此 JSON
来自 PHP 服务器。
我如何使用 Retrofit 处理它?
最佳答案
要使用动态键解析 JSON
,您的 POJO
类中需要一个 Map
。
将以下 POJO
类添加到您的项目中:
CalendarResponse.java
public class CalendarResponse { @SerializedName("calendar") Map<String, List<Entry>> entries; @SerializedName("error") private boolean error; }
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; }
在您的端点改造接口(interface)中使用
CalendarResponse
类,请参见下面的示例public interface CalendarService { @GET("<insert your own relative url>") Call<CalendarResponse> listCalendar(); }
按如下方式(同步)执行调用:
Call<CalendarResponse> call = calendarService.listCalendar(); CalendarResponse result = call.execute().body();
如果需要,这里有一个用 GSON
解析 JSON
的例子:
Gson gson = new GsonBuilder().create();
CalendarResponse b = gson.fromJson(json, CalendarResponse.class);
关于android - 如何在 Retrofit 中使用 Gson 转换器解析关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37883748/