Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how check is the json Array available and exist?

Tags:

json

android

I'm loading a json array in my app.but i need to know if the json array is exist or not? because if the json array isn't exist, the app will crash.

for example, I have this json:

{ 
"music1":
    [
    {
    "art":"",
                 "artist":"",
    "music":"",
     "flag":"",
                 "text":"",
                 "level":""
 }, 
    {
    "art":"",
                 "artist":"",
    "music":"",
    "flag":"",
                 "text":"",
                 "level":""
 },
]
}

and I want to know is there any json object named "music1" in my code or not, and then if there was I want to get the json array and show it in a list in my android app.

I'm looking forward a hero that could help me!

like image 790
Mostafa Shakoori Avatar asked Oct 16 '25 23:10

Mostafa Shakoori


1 Answers

I wish this explanation would fit in a comment.

Anyway:

{ 
"music1":
    [
    {
    "art":"",
                 "artist":"",
    "music":"",
     "flag":"",
                 "text":"",
                 "level":""
 }, 
    {
    "art":"",
                 "artist":"",
    "music":"",
    "flag":"",
                 "text":"",
                 "level":""
 }
]
}

Let call the above json object o. So to check if o has music1, all you need to check is write the following line:

if(o.has("music1")){
   JSONArray array= o.getJSONArray("music1");
}

Then you extract the objects of the json array :

for(int i=0;i<array.length();i++){
     array.getJSONObject(i);
}
like image 109
Miriana Itani Avatar answered Oct 19 '25 12:10

Miriana Itani