2016-11-30 108 views
-2

我有一个清洁,简单的问题,如何阅读本采用Android改造2.0Android的改造阅读JSON对象

{ 
    "status": true, 

"body": { 

    "expertises": { 
     "1": "Family Law", 
     "2": "Land and Asset", 
     "3": "Sexual Offense" 
    } 
    } 
} 

我想读

我已经使用的模型类如下“专长”: 专长:

​​

ExpertisesResponse:

public class ExpertisesResponse { 

    @SerializedName("1") 
    private String expertiseOne; 
    @SerializedName("2") 
    private String expertiseTwo; 
    @SerializedName("3") 
    private String expertiseThree; 

    public String getExpertiseOne() { 
     return expertiseOne; 
    } 

    public ExpertisesResponse(String expertiseOne, String expertiseTwo, String expertiseThree) { 
     this.expertiseOne = expertiseOne; 
     this.expertiseTwo = expertiseTwo; 
     this.expertiseThree = expertiseThree; 
    } 



    public String getExpertiseTwo() { 
     return expertiseTwo; 
    } 

    public String getExpertiseThree() { 
     return expertiseThree; 
    } 

    public void setExpertiseOne(String expertiseOne) { 
     this.expertiseOne = expertiseOne; 
    } 

    public void setExpertiseTwo(String expertiseTwo) { 
     this.expertiseTwo = expertiseTwo; 
    } 

    public void setExpertiseThree(String expertiseThree) { 
     this.expertiseThree = expertiseThree; 
    } 
} 

但我得到了ExceptionisesResposne的Exception NullPointer。 PLease我想要一些改进或更正,如果有任何错误。

这是我怎么叫:

ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class); 
     Call<Expertises> getExpertises = apiInterface.getExpertise(); 
     getExpertises.enqueue(new Callback<Expertises>() { 
      @Override 
      public void onResponse(Call<Expertises> call, Response<Expertises> response) { 

       Toast.makeText(getApplicationContext(),response.body().getExpertisesResponse().getExpertiseOne(),Toast.LENGTH_SHORT).show(); 

      } 

      @Override 
      public void onFailure(Call<Expertises> call, Throwable t) { 

      } 
     }); 
    } 
+0

你创建的模型类该类? – PriyankaChauhan

+0

是的,但如果你能说出来会更好,因为我对“专家”有困惑 – Danish

+0

专家的数量是否随时间而变化?这些总是有3个? –

回答

0

你错过了类Body覆盖类ExpertisesResponse。应该是这样的:

class Body { 

@SerializedName("expertises") 
    ExpertisesResponse expertisesResponse; 

} 

而且Expertises

public class Expertises { 
    @SerializedName("status") 
    private String status; 
    @SerializedName("body") 
    Body body; 
} 
+0

谢谢你的工作!现在最后一件事是,如果将来JSON响应中的这些“专家”会增加?如何适应这种情况? – Danish

+0

如果'expertises'中的值发生变化。有两种方法可以做到:1-重构你的json,使用''key''返回。 2.手动解析动态密钥(需要手动解析)[链接] http://stackoverflow.com/questions/7304002/how-to-parse-a-dynamic-json-key-in-a-nested-json-结果。我认为如果你使用自动解析的改造,你建议你的第一种方法。 –

+0

好的谢谢罗山珊:) – Danish