所有我會假設你現在有什麼樣的意見後:
{
"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
我無法確定,但我想你可以從這個例子中理解。也請添加適當的獲取者和設置者。
我希望您專注於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實際上是上面的那個。
改造界面改變了一點,但它本質上是相同的思路前:
public interface EventService {
@GET("/url/to/events/endpoint/")
public Call<Event> get();
}
一旦你enqueue
的要求和定義Callback
對象,你會在你成功得到Event
對象方法可以參考一個場地。下面是這些回調可能與改造實現(可能會略有改進版本之間的變化我不完全記):
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對象中。希望能幫助到你。
取決於...我有幾個問題,那麼我可能會提供幫助。你是否在使用Gson的Retrofit?你的休息api實際上是返回上面的jsons,還是序列化的結果?我的意思是,服務器是否可能不會向您發送嵌套的json?你已經有一些模型? – Fred
是的,我正在使用Gson改造。其他api返回json,如上所示。它不會發送嵌套的json。 – zacmwa
好的,改造不會爲你開箱即用。你有2個選項,看看第一個調用是否支持一些參數,或者是頭部會告訴服務器他應該在響應中包含''venue'' json。如果是這樣,那麼幫助會更容易。如果沒有,那麼你必須找出你如何獲得該場所的ID,因爲很可能你必須再打一次休息電話。我會採用第一種方法,試着弄清楚在第一個電話的回覆中是否可以包含場地的身體。讓我知道,我會進一步幫助你。 – Fred