【问题标题】:Android Retrofit - How to seperate classes from JSON ArrayAndroid Retrofit - 如何从 JSON 数组中分离类
【发布时间】:2017-07-15 10:28:47
【问题描述】:

尝试通过以下方式访问 JSON 数据:

{"actions":[{"actionType":0,"email":"contact@tonyspizza.com","faIcon":"fa-envelope",
"name":"Contact Us","subject":"Email from Tony's Pizza App"},
{"actionType":2,"faIcon":"fa-phone","name":"Call Us","number":"5204558897"}],
"total":2}

我正在尝试使用改造来访问“动作”作为每个单独的类。 (即 ActionEmail、ActionPhone 等)。我想不出一种方法将它们分成单独的类,并且没有一个具有所有属性的类。

提前致谢!

【问题讨论】:

  • R u 使用任何 Json 解析器,如 Gson 并进行改造?
  • 签出this
  • 是的,我正在使用带有 Retrofit 的 Gson。它希望将所有数据放在一个动作类下,但我的目标是根据每种动作类型创建一个单独的类。即:对于actionType = 0,它将使用ActionEmail 类,对于actionType = 2,它将使用ActionCall,等等...感谢您的及时回复。

标签: java android json retrofit


【解决方案1】:
 Call<ActionWrapperObject> getActions(// Put your api call body in there);

这是你的ActionWrapperObject

public class ActionWrapperObject {
    ArrayList<ActionModel> actions;

    public ArrayList<ActionModel> getActions() {
        return actions;
    }

    public void setActions(ArrayList<ActionModel> actions) {
        this.actions = actions;
    }
}

这是你的ActionModel

public class ActionModel {

    int actionType;
    String email;
    String faIcon;
    String name;
    String subject;

    public int getActionType() {
        return actionType;
    }

    public void setActionType(int actionType) {
        this.actionType = actionType;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFaIcon() {
        return faIcon;
    }

    public void setFaIcon(String faIcon) {
        this.faIcon = faIcon;
    }

    public String getName() {
        return name;
    }

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

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }
}

你的回应

Your api call.enqueue(new Callback<ActionWrapperObject>() {
                    @Override
                    public void onResponse(Call<ActionWrapperObject> call, Response<ActionWrapperObject> response) {
                        ActionWrapperObject actionWrapperObj= response.body();
                        if (actionWrapperObj!= null) {
                          ArrayList<ActionModel> actionModelList= actionWrapperObj.getActions();
//Here you got the list of actions. Do what ever you want with them. You can 
// differentiate each action on its type.
                                                    }
                    }

【讨论】:

  • 这很好,我已经实现了类似的解决方案。但是,这也仅基于 2 个 ActionTypes.... 如果我想增加 ActionTypes 的数量怎么办?这个班级不会变得庞大吗?当它开始增长到许多 actionTypes 时,它看起来就是错误的......感谢您的回复!
【解决方案2】:

我推断您想要动态生成 ActionModel 类的字段。可以参考使用反射动态生成 JSON pojo。

【讨论】:

    猜你喜欢
    • 2014-08-29
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多