如何将 Retrofit 响应映射到数据模型类? [英] How do I map Retrofit response to Data Model Class?

查看:71
本文介绍了如何将 Retrofit 响应映射到数据模型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的改造电话...

 public void getContests() {
        String token = LoginActivity.authToken;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(OctoInterface.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        OctoInterface api = retrofit.create(OctoInterface.class);

        Call<List<OctoModel2>> call = api.getOctoContests(token);



        call.enqueue(new Callback<List<OctoModel2>>() {
            @Override
            public void onResponse(Call<List<OctoModel2>> call, Response<List<OctoModel2>> response) {
                int statusCode = response.code();
                int i = 0;
                if (response.body().size() > titleList.size()) {
                 for (i = 0; i <= response.body().size() -1; i++) {

                     contestIdList.add(String.valueOf(response.body().get(i).getId()));
                    titleList.add(response.body().get(i).getTitle());

                    subtitleList.add(response.body().get(i).getDescShort());
                    offerIdList.add(String.valueOf(response.body().get(i).getId()));
                    offerLogoList.add(response.body().get(i).getLogoUrl());
                    businessId = String.valueOf(response.body().get(i).getBusinessId());
                    submit_button_text = response.body().get(i).getSubmitButtonText();
                    }
                }
            }

            @Override
            public void onFailure(Call<List<OctoModel2>> call, Throwable t) {
                Log.e("Get Contest failure", call.toString());
                t.printStackTrace();
            }
        });
    }

如您所见,我目前正在获取我需要的响应片段并将它们传递给各个数组列表.我更愿意将整个返回传递到保存数据的模型对象列表中.

As you can see, I'm currently grabbing the pieces of the response that I need and passing them to individual array lists. I'd much rather pass the entire return into a list of model objects that hold the data.

这是我用于改造的 POJO 类...

Here is my POJO class for retrofit...

public class OctoModel2 {

    @SerializedName("how_it_works")
    @Expose
    private List<String> howItWorks = null;
    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("business_id")
    @Expose
    private int businessId;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("desc_short")
    @Expose
    private String descShort;
    @SerializedName("logo_url")
    @Expose
    private String logoUrl;
    @SerializedName("hashtag")
    @Expose
    private String hashtag;
    @SerializedName("confirm_message_title")
    @Expose
    private String confirmMessageTitle;
    @SerializedName("rules")
    @Expose
    private String rules;
    @SerializedName("confirm_message")
    @Expose
    private String confirmMessage;
    @SerializedName("start_date")
    @Expose
    private String startDate;
    @SerializedName("end_date")
    @Expose
    private String endDate;
    @SerializedName("active")
    @Expose
    private boolean active;
    @SerializedName("entry_count")
    @Expose
    private int entryCount;
    @SerializedName("age_required")
    @Expose
    private int ageRequired;
    @SerializedName("submit_button_text")
    @Expose
    private String submitButtonText;
    @SerializedName("hide_redeem_code")
    @Expose
    private boolean hideRedeemCode;
    @SerializedName("redeem_button_text")
    @Expose
    private String redeemButtonText;
    @SerializedName("rules_text")
    @Expose
    private String rulesText;
    @SerializedName("mode")
    @Expose
    private String mode;
    @SerializedName("entry_mode")
    @Expose
    private String entryMode;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("locations")
    @Expose
    private List<Location> locations = null;
    @SerializedName("entries")
    @Expose
    private List<Entry> entries = null;
    @SerializedName("entry")
    @Expose
    private Entry entry;
    @SerializedName("AWSAccessKeyId")
    @Expose
    private String aWSAccessKeyId;
    @SerializedName("key")
    @Expose
    private String key;
    @SerializedName("policy")
    @Expose
    private String policy;
    @SerializedName("signature")
    @Expose
    private String signature;
    @SerializedName("uuid")
    @Expose
    private String uuid;
    @SerializedName("reward")
    @Expose
    private Reward reward;
    @SerializedName("s3_url")
    @Expose
    private String s3_url;

    public OctoModel2(Integer id, Integer businessId, String title, String descShort, String logoUrl, String hashtag, String confirmMessageTitle, String rules, String confirmMessage, String startDate, String endDate, Boolean active,
                      String submitButtonText, String redeemButtonText, String rulesText, List<Location> locations, String aWSAccessKeyId, String key, String policy, String signature, String uuid) {
        this.id = id;
        this.businessId = businessId;
        this.title = title;
        this.descShort = descShort;
        this.logoUrl = logoUrl;
        this.hashtag = hashtag;
        this.confirmMessageTitle = confirmMessageTitle;
        this.rules = rules;
        this.confirmMessage = confirmMessage;
        this.startDate = startDate;
        this.endDate = endDate;
        this.active = active;
        this.submitButtonText = submitButtonText;
        this.redeemButtonText = redeemButtonText;
        this.rulesText = rulesText;
        this.locations = locations;
        this.aWSAccessKeyId = aWSAccessKeyId;
        this.key = key;
        this.policy = policy;
        this.signature = signature;
        this.uuid = uuid;
    }

    public List<String> getHowItWorks() {
        return howItWorks;
    }

    public void setHowItWorks(List<String> howItWorks) {
        this.howItWorks = howItWorks;
    }

    public int getId() {
        return id;
    }

    public List<OctoModel2> getResults() {
        return results;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getBusinessId() {
        return businessId;
    }

    public void setBusinessId(int businessId) {
        this.businessId = businessId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescShort() {
        return descShort;
    }

    public void setDescShort(String descShort) {
        this.descShort = descShort;
    }

    public String getLogoUrl() {
        return logoUrl;
    }

    public void setLogoUrl(String logoUrl) {
        this.logoUrl = logoUrl;
    }

    public String getHashtag() {
        return hashtag;
    }

    public void setHashtag(String hashtag) {
        this.hashtag = hashtag;
    }

    public String getConfirmMessageTitle() {
        return confirmMessageTitle;
    }

    public void setConfirmMessageTitle(String confirmMessageTitle) {
        this.confirmMessageTitle = confirmMessageTitle;
    }

    public String getRules() {
        return rules;
    }

    public void setRules(String rules) {
        this.rules = rules;
    }

    public String getConfirmMessage() {
        return confirmMessage;
    }

    public void setConfirmMessage(String confirmMessage) {
        this.confirmMessage = confirmMessage;
    }

    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;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public int getEntryCount() {
        return entryCount;
    }

    public void setEntryCount(int entryCount) {
        this.entryCount = entryCount;
    }

    public int getAgeRequired() {
        return ageRequired;
    }

    public void setAgeRequired(int ageRequired) {
        this.ageRequired = ageRequired;
    }

    public String getSubmitButtonText() {
        return submitButtonText;
    }

    public void setSubmitButtonText(String submitButtonText) {
        this.submitButtonText = submitButtonText;
    }

    public boolean isHideRedeemCode() {
        return hideRedeemCode;
    }

    public void setHideRedeemCode(boolean hideRedeemCode) {
        this.hideRedeemCode = hideRedeemCode;
    }

    public String getRedeemButtonText() {
        return redeemButtonText;
    }

    public void setRedeemButtonText(String redeemButtonText) {
        this.redeemButtonText = redeemButtonText;
    }

    public String getRulesText() {
        return rulesText;
    }

    public void setRulesText(String rulesText) {
        this.rulesText = rulesText;
    }

    public String getMode() {
        return mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

    public String getEntryMode() {
        return entryMode;
    }

    public void setEntryMode(String entryMode) {
        this.entryMode = entryMode;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Location> getLocations() {
        return locations;
    }

    public void setLocations(List<Location> locations) {
        this.locations = locations;
    }

    public List<Entry> getEntries() {
        return entries;
    }

    public void setEntries(List<Entry> entries) {
        this.entries = entries;
    }
    public Entry getEntry() {
        return entry;
    }
    public String getAWSAccessKeyId() {
        return aWSAccessKeyId;
    }

    public void setAWSAccessKeyId(String aWSAccessKeyId) {
        this.aWSAccessKeyId = aWSAccessKeyId;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getPolicy() {
        return policy;
    }

    public void setPolicy(String policy) {
        this.policy = policy;
    }

    public String getSignature() {
        return signature;
    }

    public String gets3url() {
        return s3_url;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }
    public Reward getReward() {
        return reward;
    }

    public void setReward(Reward reward) {
        this.reward = reward;
    }
    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}

而不是像

TitleList.get(position);
SubtitleList.get(position);
LogoUrlList.get(position);
etc... 

我想打电话

Contests.get(position).getTitle();
Contests.get(position).getSubtitle();
Contests.get(position).getLogoUrl();

或者无论如何.这将使我更好地对响应进行排序并从单个响应中获取数据,而无需希望和祈祷我从正确的 ArrayList 中提取了正确的项目.

or however it would be. This would make it better for me to sort the responses and get the data from individual responses without hoping and praying that I'm pulling the correct item from the correct ArrayList.

推荐答案

您需要一个映射您的 DTO 的映射器 (数据传输对象) 转换为实体或实体列表.例如:

You need a mapper that maps your DTO (Data Transfer Object) into an entity or list of entities. For example:

public interface Mapper<From, To> {
    To map(From value);
}

现在您可以创建一个类,例如称为`MyRetrofitResponseMapper,它实现了接口并映射了所需的字段.

Now you can create a class, e.g. called `MyRetrofitResponseMapper, that implements the interface and maps the fields needed.

此外,您可以创建多个映射器,将相同的 DTO 映射到不同的实体,具体取决于这些实体所需的 DTO 字段.

Moreover, you can create multiple mappers that map the same DTO into different entities depending on what DTO fields are required for those.

可以在此处找到示例.

这篇关于如何将 Retrofit 响应映射到数据模型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆