2016-11-30 133 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