2017-05-02 63 views
-3

我想要獲取來自API服務的所有數據,但我在訪問JSON響應中的不同「級別」時遇到問題。Android:在JSON響應中訪問級別

我相信我的主要問題是當內部級別包括[]

我在這裏展示的JSON響應(整個反應是巨大的)的減少部分。但是,這部分代表清楚我的問題

{ 
   「CustomerList」:{ 
      「CustomerType」:」residential」, 
      「maxAllowed」:」256」, 
      "serverdate":"2017-05-02", 
      「Purchases」:[ 
         { 
            「Car」:[ 
               { 
                  「customerName」:」Fredrik」, 
                  「price」:」25890」, 
                  「currency」:」EUR」, 
                  「Item」:{ 
                     「code」:」Audi」, 
                     「model」:」A3」, 
                     「engine」:」diesel」, 
                     「data」:」2017-03-12」, 
                     "$":"\n" 
                  }, 
                  "Destination":{ 
                     「country」:」Germany」, 
                     「arrivalDate」:」March 25」, 
                     "id":"02201403", 

我已經能夠訪問CustomerListPurchases這樣

JSONObject customer = (JSONObject) response.get("CustomerList"); 
    JSONArray purchases = customer.getJSONArray("Purchases"); 

但是訪問內部領域,如CarItemDestination和它們的元素,現在我正在煩惱。

下面給我JSONException

for (int i = 0;i< purchases.length();i++){ 
     JSONObject car = purchases.getJSONObject(i); 
     String custName = car.getString("customerName"); 
+0

可能的重複[如何解析Java中的JSON](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java ) –

回答

1

在你的情況,你得到了錯誤的對象,

採購是一個JSONArray誰包含的對象假設類Purchase。它的每個實例都有一個名爲Car的JSONArray(包含Cars)的實例。

鑑於此,該地訪問的第一車:

for (int i = 0;i< purchases.length();i++){ 
    JSONObject p = purchases.getJSONObject(i); 
    JSONObject car = p.getJSONObject(0); 
    String custName = car.getString("customerName"); 

我鼓勵你強烈地使用JSON序列像gson以避免這些問題的處理。看看jsonschema2pojo來生成你的層次的類

+0

感謝您的答案cgarrido,從您的鏈接我可以看到,很容易創建類引用不同的'汽車',但如何使用它們的代碼?,你的第一個鏈接'gson'不工作 – codeKiller

+0

我只是修復了鏈接。 Gson非常易於使用,在網絡中查找示例。這可能對您有所幫助https://www.javacodegeeks.com/2013/08/getting-started-with-google-gson.html。請投我的答案,如果它幫助你 – crgarridos

+0

是的,它幫助和實際上解決了我的問題,投票和接受!,謝謝。 – codeKiller

1

汽車是JSONArray,而不是JSONObject

for (int i = 0;i< purchases.length();i++){ 
     JSONArray array = purchases.getJSONArray(i); 
     for (int j = 0; j < array.length(); j++){ 
      // loop through here again to get the JSONObject  
     } 
} 

在內部循環,你會得到JSONObject並且可以調用
String custName = array.getJSONObject(j).getString("customerName");

如果你看看例外情況,你會問巧妙地看到類似
you cannot cast a ... to a JSONObject

0

車也JSONArray所以儘量象下面這樣:

for (int i = 0;i< purchases.length();i++){ 
      JSONArray carArr = purchases.getJSONArray(i); 
      for (int j = 0;j< carArr.length();j++){ 
      JSONObject car = carArr.getJSONObject(j); 
      String custName = car.getString("customerName"); 
      } 
    }