how to check if a JSONArray is empty in java?

前端 未结 4 905
温柔的废话
温柔的废话 2021-01-01 11:28

I am working on an android app that get json content of a webservice called \"WebUntis\". The Json content i am getting looks like:

{\"jsonrpc\":\"2.0\",\"id         


        
4条回答
  •  自闭症患者
    2021-01-01 12:17

    If the array is defined in the file but is empty, like:

    ...
    "kl":[]
    ...
    

    Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:

    kl = c.getJSONArray("kl");
    if(kl != null){
       klassenID[i] = kl.getJSONObject(0).getString("id");
    }
    

    kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.

    Instead you can check the length(), e.g.:

    kl = c.getJSONArray("kl");
    if(kl != null && kl.length() > 0 ){
       klassenID[i] = kl.getJSONObject(0).getString("id");
    }
    

提交回复
热议问题