My program gives error when array value is null

0

I have a program that pulls reports from a system, I'm including one more table in the program. The data that is read comes from an array but sometimes it is empty, and when it does, 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 of error:

  

Source not found

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

in this line and the program stops rolling.

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");
                }
    
asked by anonymous 20.03.2017 / 17:57

2 answers

0

Good afternoon, you can use the has property to validate if 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");
                        }
                    }
                }
            }
      }
    
20.03.2017 / 20:20
0

I do not know if this could 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);
}
    
20.03.2017 / 18:10