我得到一個來自服務器的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數組存在的對象。我確信我可以做一些類型的遞歸解決方案,但這仍然很煩人。任何建議?