30

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":"req-002",
 "result":[
    {"id":125043,"date":20110117,"startTime":800,"endTime":850,
     "kl":[{"id":71}],
     "te":[{"id":23}],
     "su":[{"id":13}],
     "ro":[{"id":1}]},
    {"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
     "kl":[{"id":71}],
     "te":[{"id":41}],
     "su":[{"id":19}],
     "ro":[{"id":31}]},
...]}

As you can see in the result-array there are also other arrays like "kl", "su" and "ro"

I am getting the content of these array and then i store them in an arraylist. But when one of these array is empty, like;

    {"jsonrpc":"2.0","id":"req-002",
     "result":[
         {"id":125043,"date":20110117,"startTime":800,"endTime":850,
          "**kl":[]**,
          "te":[{"id":23}],
          "su":[{"id":13}],
          "ro":[{"id":1}]},
         {"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
          "kl":[{"id":71}],
          "te":[{"id":41}],
          "su":[{"id":19}],
          "ro":[{"id":31}]},
...]}

I am always getting the error IndexOutOfRangeException, but I am always telling it that it should not take the empty arrays, this is what I have tried:

 JSONObject jsonResult = new JSONObject(s);
 // Get the result object
 JSONArray arr = jsonResult.getJSONArray("result");

 for (int i = 0; i < arr.length(); i++) {
    JSONObject c = arr.getJSONObject(i);
    anfangStunde[i] = c.getString("startTime");
    endeStunde[i] = c.getString("endTime");

    // get the jsonarrays (kl, su, ro)
    kl = c.getJSONArray("kl");
    su = c.getJSONArray("su");
    ro = c.getJSONArray("ro");

    // check if kl is not null
    if(kl != null){
       klassenID[i] = kl.getJSONObject(0).getString("id");
    }
    if (klassenID[i] != null) {
       klasse = webuntis.klassenMap.get(klassenID[i]);
       Log.d("ID und Klasse=", "" + klassenID[i] + ";" + klasse);
    }
    // get th ids
    fachID[i] = su.getJSONObject(0).getString("id");
    if (fachID[i] != null) {
       fach = webuntis.faecherMap.get(fachID[i]);
       Log.d("ID und Fach=", "" + fachID[i] + ";" + fach);
    }

    // "Start;Ende;Klasse;Fach;Raum" store in arraylist
    webuntis.stundenPlan.add(anfangStunde[i] + ";" + endeStunde[i] + ";" + klasse + ";" + fach);
    // Write Data into a file for offline use:
 }

Can anyone help me ?

5 Answers 5

55

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice work if(kl != null && kl.length() > 0 ){ simple
1

You can also use isEmpty() method, this is the method we use to check whether the list is empty or not. This method returns a Boolean value. It returns true if the list is empty otherwise it gives false. For example:

if (!k1.isEmpty()) {
    klassenID[i] = kl.getJSONObject(0).getString("id");     
}

Comments

1

You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not. This also keeps you in track of total elements in the Array, You wont go out of Index.

if(k1 != null && k1.length != 0){
     //Do something.
}

Comments

0

This is another way to do it...

call.enqueue(new Callback<JsonObject>() {
    @Override
    public void onResponse(Call<JsonObject> call,
                           Response<JsonObject> response) {

        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(new Gson().toJson(response.body()));


            JSONArray returnArray = jsonObject.getJSONArray("my_array");

            // Do Work Only If Not Null
            if (!returnArray.isNull(0)) {

                for (int l = 0; l < returnArray.length(); l++) {
                    if (returnArray.length() > 0) {

                        // Get The Json Object
                        JSONObject returnJSONObject = returnArray.getJSONObject(l);

                        // Get Details
                        String imageUrl = returnJSONObject.optString("image");

                    }
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onFailure(Call<JsonObject> call,
                          Throwable t) {

    }
});

Comments

0

If you are using JSONObject and JSONArray from org.json and you have an object like this

{
   "createdBy": "4fgdfgdfgd",
   "customers" : null //here customer is supposed to be an array, []
}

Then you can do a check like this

if(jsonObject.get("customers")==JSONObject.NULL) {
   //do something if it is null
}

JSONObject.NULL is a built in constant present in org.json package

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.