I am getting a JSON response back from a server and the array I need to grab is a value embedded deep inside multiple objects and arrays. I need to grab the formatIds JSONArray. My JSON looks like this:
{
"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"
]
}
}
}
]
}
]
}
]
}
The only way I have been able to figure out is to have a bunch of embedded for loops:
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);
}
}
}
}
This code REALLY REALLY slow x20 because of all the embedded loops. Is there a way for me to get this JSONArray without having to have this extra code?? In jQuery there is a JSON.find and was wondering if there something similar to this in Java? I have tried the JSON API calls getJSONArray and get on the root jsonObject but it doesn't work unless you are in object in which the json array exists. I'm sure I could do some type of recursive solution but this is still annoying. Any advice??