2012-07-18 68 views
0

我得到一個來自服務器的JSON響應,我需要獲取的數組是一個嵌入多個對象和數組內部的值。我需要抓取formatIds JSONArray。我的JSON看起來是這樣的:獲取嵌入到多個對象/數組中的JSONArray

{ 
    "entries": [ 
     { 
      "title": "sample", 
      "targets": [ 
       { 
        "format": "wav",`enter code here` 
        "description": "A wav file", 
        "formatCriteria": [ 
         { 
          "formatSelectionTitle": "Find WAV files", 
          "formatSteps": { 
           "UniqueId": "214212312321", 
           "formatMatches": { 
            "formatIds": [ 
             "WAV", 
             "MP3" 
            ] 
           } 
          } 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

我已經能夠想出的唯一辦法就是有一堆的嵌入式for循環:

String[] assetUri; 
for (int i = 0; i < entriesArray.length(); i++) { 
    entryJsonOjbect = entriesArray.getJSONObject(i); 
    fileTargetArray = tempObj.getJSONArray("targets"); 
    //Loop through the targets array 
    for (int j = 0; j < fileTargetArray.length(); j++) { 
     tempObj = fileTargetArray.getJSONObject(j); 
     fileCriteriaArray = tempObj.getJSONArray("formatCriteria"); 
     //Loop through fileCriteria Array 
     for (int h = 0; h < fileCriteriaArray.length(); h++) { 
      JSONObject fileCriteriaObj = fileCriteriaArray.getJSONObject(h); 
      //Get the JSON Object 'formatSteps' 
      JSONObject selectStepObj = fileCriteriaObj.getJSONObject("formatSteps"); 
      //Get the JSON Object 'formatMatches' 
      JSONObject selectionMatches = selectStepObj.getJSONObject("formatMatches"); 
      //FINALLY. Get the formatIds ARray 
      JSONArray assetTypeArray = selectionMatches.getJSONArray("formatIds"); 
       //Assign the values from the JSONArray to my class 
       assetUri = new String[assetTypeArray.length()]; 
       for (int z = 0; z < assetTypeArray.length(); z++) { 
        assetUri[z] = assetTypeArray.getString(z); 
      } 

     } 
    } 
} 

此代碼,因爲所有的真的很慢X20嵌入式循環。有沒有辦法讓我得到這個JSONArray而不必擁有這個額外的代碼?在jQuery中有一個JSON.find並想知道在Java中是否有類似的東西?我已經嘗試過JSON API調用getJSONArray得到在根jsonObject上,但它不起作用,除非你在json數組存在的對象。我確信我可以做一些類型的遞歸解決方案,但這仍然很煩人。任何建議?

回答

1

解析JSON與org.json -library就像使用DOM解析XML:一步一步。但是:你需要所有這些循環。

如果你的JSON響應總是看起來像你發佈的(每個數組中的單個元素),那麼你的JSON是非常無效的。如果您只想要「第一個」條目,請不要遍歷數組。

org.json解析這樣一個複雜的數據結構可能會很痛苦。您是否嘗試過(更自動)google-gson庫?退房the examples。雖然我不想說用gson解析它的CPU時間會更快,但在開發時間方面它的速度會更快。

我也剛剛寫了一篇博客,一篇關於這個話題:JSON and Java