We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello, I'm gathering data from an API and sometimes I run into an error that I don't fully understand.
This is the line of code that I use to access the parameter:
JSONArray primaryArtists = thisResult.getJSONObject("album").getJSONArray("primaryArtists");
It runs smoothly most of the time but sometimes I got this error: JSONObject["primaryArtists"] is not a JSONArray
But If i check the JSON file loaded this is what I see:
"album":{
"ids":{
"albumId":"MW0002184001",
"amgClassicalId":null,
"amgPopId":"R 2242331"
},
"title":"Duets II",
"primaryArtists":[
{
"id":"MN0000006334",
"name":"Tony Bennett"
}
],
}
This below is an example of a different JSON which doesn't throw the error:
"album":{
"ids":{
"albumId":"MW0002055358",
"amgClassicalId":null,
"amgPopId":"R 2029503"
},
"title":"I Am Not a Human Being",
"primaryArtists":[
{
"id":"MN0000272689",
"name":"Lil Wayne"
}
],
}
Answers
I just realised that sometimes the API returns
"primaryArtists": null
and that was giving me the problem because, of course, null is not a JSONArray.I solved this by checking if the value is null before reading it:
if (!thisResult.getJSONObject("album").isNull("primaryArtists"))
well done...!