2017-07-15 32 views
1

单独的类试图从以下访问JSON数据:Android的改造 - 如何从JSON阵列

{"actions":[{"actionType":0,"email":"[email protected]","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等)。我无法想出一种方法将它们分为单独的类,并且没有一个具有所有属性的类。

在此先感谢!

+0

使用任何像Gson这样的Json解析器进行翻新? –

+0

检查[this](http://www.pratikbutani.com/2016/05/android-tutorial-json-parsing-using-retrofit-part-1/)。 – sHOLE

+0

是的,我正在使用Gson w/Retrofit。它希望将所有数据放在一个动作类下,但我的目标是根据每个动作类型创建一个单独的类。 I.e .:对于actionType = 0,它将使用一个ActionEmail类,对于actionType = 2,它将使用ActionCall等等...... 感谢您的及时响应。 –

回答

0
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. 
                } 
        } 
+0

这很好,我已经实施了类似的解决方案。然而,这也仅仅基于2个ActionTypes ....如果我想增加ActionTypes的数量呢?这个班不会变得很庞大吗?它只是看起来错了,当它开始增长到众多actionTypes ... 感谢您的答复! –

0

我推断出什么是你想生成的场Ť他动态地为ActionModel类。您可以参考使用反射动态生成JSON pojo。