Android Retrofit - 如何从JSON数组中分离类

时间:2017-07-15 10:28:47

标签: java android json retrofit

尝试从以下位置访问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等)。我无法想出一种方法将这些分成不同的类,而没有一个具有所有属性的类。

提前致谢!

2 个答案:

答案 0 :(得分: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.
                                                    }
                    }

答案 1 :(得分:0)

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