如何在RetroFit 2中处理来自同一端点的不同JSON响应类型

时间:2018-04-19 09:15:23

标签: android

这是我的json api: - https://test324y.highape.com/api/get_homepage_data?token=xyz123

正如您所看到的,它有许多不同类型的对象。 当我将其粘贴到http://www.jsonschema2pojo.org/时,它会给我多个课程。

我想知道如何使用同一端点的改造将数据设置到那些模型类?

2 个答案:

答案 0 :(得分:0)

我建议只使用一个模型类来使用Retrofit解析响应。

实施例: 创建一个模型类,说Response.java,其中包含以下模型类:

  1. FeaturedEvents
  2. TrendingEvents
  3. PopularActivities
  4. 优惠
  5. 场地
  6. 艺术家
  7. 以上所有模型类都包含相应的数据。这样您就可以轻松地解析响应,如果API排除了响应中的任何模型,那么该模型的解析值将为null。在UI中显示之前,您应该始终检查它。

    希望这会有所帮助!

答案 1 :(得分:0)

http://www.jsonschema2pojo.org/生成Pojos后 您将获得响应中每个对象的类。但是你只会使用名为示例的类进行改造。之后您可以通过它访问所有响应值。

当然,将您的响应类重命名为与端点更相关的内容。例如" HomePageResponse"

public class Example {

@SerializedName("featured_events")
@Expose
private FeaturedEvents featuredEvents;
@SerializedName("trending_events")
@Expose
private TrendingEvents trendingEvents;
@SerializedName("popular_activities")
@Expose
private PopularActivities popularActivities;
@SerializedName("event_count")
@Expose
private EventCount eventCount;
@SerializedName("offers")
@Expose
private Offers offers;
@SerializedName("venues")
@Expose
private Venues venues;
@SerializedName("artists")
@Expose
private Artists artists;

public FeaturedEvents getFeaturedEvents() {
return featuredEvents;
}

public void setFeaturedEvents(FeaturedEvents featuredEvents) {
this.featuredEvents = featuredEvents;
}

public TrendingEvents getTrendingEvents() {
return trendingEvents;
}

public void setTrendingEvents(TrendingEvents trendingEvents) {
this.trendingEvents = trendingEvents;
}

public PopularActivities getPopularActivities() {
return popularActivities;
}

public void setPopularActivities(PopularActivities popularActivities) {
this.popularActivities = popularActivities;
}

public EventCount getEventCount() {
return eventCount;
}

public void setEventCount(EventCount eventCount) {
this.eventCount = eventCount;
}

public Offers getOffers() {
return offers;
}

public void setOffers(Offers offers) {
this.offers = offers;
}

public Venues getVenues() {
return venues;
}

public void setVenues(Venues venues) {
this.venues = venues;
}

public Artists getArtists() {
return artists;
}

public void setArtists(Artists artists) {
this.artists = artists;
}

}

您的终端将是这样的。

@GET("get_homepage_data")
Call<Example> getExample(@Query("token") String token);

端点呼叫示例

   Call<Example> call = api.getExample(token);
    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {
            Example example = response.body();
            // use example object to get any value you want

        } 

        @Override
        public void onFailure(Call<HyperResponse> call, Throwable t) {
            if (t != null && t.getMessage() != null)
                Log.e("Failure", "Example Failure" + t.getMessage());
        }
    });