如何在Retrofit(Android)中没有任何键的情况下获取JSON数组?

时间:2017-02-13 12:54:44

标签: android json retrofit2

我有JSON array没有任何对象(键),其中JSON Objects就像这样:

[
  {
    "Type": "Meeting",
    "Name": "TestMeeting",
    "StartDate": "2016-03-22T08:00:00",
    "EndDate": "2016-03-24T09:00:00"
  }
]

我尝试解析但无法获得成功,有人可以建议我如何使用Retrofit解析此类响应吗?

3 个答案:

答案 0 :(得分:12)

您可以定义代表JSON对象的Class

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Meeting{

@SerializedName("Type")
@Expose
private String type;
@SerializedName("Name")
@Expose
private String name;
@SerializedName("StartDate")
@Expose
private String startDate;
@SerializedName("EndDate")
@Expose
private String endDate;

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getStartDate() {
return startDate;
}

public void setStartDate(String startDate) {
this.startDate = startDate;
}

public String getEndDate() {
return endDate;
}

public void setEndDate(String endDate) {
this.endDate = endDate;
}

}

之后你就像那样定义Callback进行改造 Call<List<Meeting>> getMeetings();

答案 1 :(得分:0)

如果您正在使用Gson解析,则可以像这样简单地完成

 var model = Gson().fromJson(response.body()!!.string(), Array<Meeting>::class.java).toList()

答案 2 :(得分:0)

Json响应:

{"contacts":{"918888302649":0,"917207251056":0,"918888804581":0}}

POJO类别:

public class ContactSyncResponseModel {

    @SerializedName("contacts")
    @Expose
    private Map<String, String> result;

    public Map<String, String> getResult() {
        return result;
    }

    public void setResult(Map<String, String> result) {
        this.result = result;
    } }