My program gives error when the array value is null

Asked

Viewed 281 times

0

I have a program that takes reports from a system, I’m including one more table in the program. The data that is read, comes from a array but sometimes it is empty, and when it gives this the program gives error.

I put an if to check if the variable is null, because if it is it will take the value of another table.

But when I debugged he accused error:

Source not found

JSONObject js2 = js.getJSONObject("cliente").getJSONArray("enderecoList").getJSONObject(0);

on that line and the program stops running.

for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject js = jsonArray.getJSONObject(i);
            JSONObject js2 = js.getJSONObject("cliente").getJSONArray("enderecoList").getJSONObject(0);
            JSONObject js3;
                if (js2 == null){
                    js3 = js.getJSONObject("unidade").getJSONObject("municipio");
                } else {
                    js3 = js2.getJSONObject("municipio");
                }

2 answers

0

I don’t know if that can be, but there is a JSON method to check if the value is NULL. The method is isNull();

For example:

if(jsonObject.isNull("parentId")){
   jsonObject.put("parentId", 0);
}
  • I tried to use the method, but it points out that it is incompatible and that a variable of type String is needed.

0


Good afternoon, you can use the property has to validate whether the attribute exists within json.

Follows:

    JSONArray jsonArray = null;

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject js = jsonArray.getJSONObject(i);
            JSONObject js3;

            if (js.has("unidade")) {
                JSONObject unidadeJson = js.getJSONObject("unidade");
                if (unidadeJson.has("municipio")) {
                    js3 = unidadeJson.getJSONObject("municipio");
                }
            }

            if (js.has("cliente")) {
                JSONObject jsonClient = js.getJSONObject("cliente");
                if (jsonClient.has("enderecoList") && !jsonClient.isNull("enderecoList")) {
                    JSONArray enderecoArray = jsonClient.getJSONArray("enderecoList");
                    if (enderecoArray.length() > 0) {
                        JSONObject js2 = enderecoArray.getJSONObject(0);
                        if (js2.has("municipio")) {
                            js3 = js2.getJSONObject("municipio");
                        }
                    }
                }
            }
      }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.