在所有的 cmets 之后,我假设现在你有类似的东西:
{
"name": "",
"time": null,
"event_pic_url": null,
"description": "",
"event_type": null,
"invite_only": false,
"free": false,
"age_restriction": false,
"ticket_price": null,
"venue": {
"name": "",
"rating": null,
"longitude": null,
"latitude": null
}
}
由于您使用的是Gson,因此您需要以下型号
public class Venue {
@SerializedName("name")
@Expose
private String name;
@SerializedName("rating")
@Expose
private Integer rating;
@SerializedName("longitude")
@Expose
private Double longitude;
@SerializedName("latitude")
@Expose
private Double latitude;
// ...
}
public class Event {
@SerializedName("name")
@Expose
private String name;
@SerializedName("time")
@Expose
private String time;
@SerializedName("event_pic_url")
@Expose
private String eventPicUrl;
@SerializedName("description")
@Expose
private String description;
@SerializedName("event_type")
@Expose
private String eventType;
@SerializedName("invite_only")
@Expose
private Boolean inviteOnly;
@SerializedName("free")
@Expose
private Boolean free;
@SerializedName("age_restriction")
@Expose
private Boolean ageRestriction;
@SerializedName("ticket_price")
@Expose
private Double ticketPrice;
@SerializedName("venue")
@Expose
private Venue venue;
// ...
}
请注意,我在这里假设了一些数据类型,即 latitude 和 longitude 以及 event_type。因为在 json 中它们是 null 我不能确定,但我想你可以从这个例子中理解。另外请添加适当的 getter 和 setter。
我希望您专注于 venue 部分。如您所见,我基本上是在 Java 对象中重新创建“嵌套”json 部分。仅此而已,Gson 和 retrofit 将为您完成剩下的工作。就是这样。请注意 - 这可能会因您的工作方式而有很大差异。我更喜欢rxjava,但这里我会使用回调方法,因为它更容易解释。
改造1.9你可以这样做:
public interface EventService {
@GET("/url/to/events/endpoint/")
public void get(Callback<Event> callback);
}
如果一切顺利,在您的回调的 success 方法上,您将获得一个 Event 的实例,您可以在其中访问 Venue 对象,前提是返回的 json 实际上是上面的那个。
改造2界面略有变化,但本质上还是和以前一样:
public interface EventService {
@GET("/url/to/events/endpoint/")
public Call<Event> get();
}
一旦您enqueue 请求并定义Callback 对象,您还将在成功方法中获得一个Event 对象,该对象将引用一个场所。以下是使用 Retrofit 2 实现这些回调的方式(可能在不同的改造版本之间略有不同。我不完全记得了):
eventService.get().enqueue(new Callback<Event>() {
@Override public void onResponse(Call<Event> call, Response<Event> response) {
if (!response.isSuccessful()) {
// Handle http error
return;
}
Event event = response.body();
Venue venue = event.getVenue();
// do something with it
}
@Override public void onFailure(Call<Event> call, Throwable t) {
// Handle error
}
});
}
这里eventService是Retrofit.create(EventService.class)创建的对象。
同样,改造位可能会根据您要使用的方法而改变。重要的是要了解如何从 json 响应映射到 java 对象,基本上你只需要复制相同的 json 结构但在 java 对象中。希望对您有所帮助。