0

Tenho um programa que retira relatórios de um sistema, estou incluindo mais uma tabela no programa. Os dados que são lidos, vem de um array mas as vezes ele está vazio, e quando dá isso o programa dá erro.

Coloquei um if para verificar se a variável está null, pois se estiver ele pegará o valor de outra tabela.

Mas quando debuguei ele acusou erro:

Source not found

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

nessa linha e o programa para de rodar.

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 Respostas 2

0

Boa tarde, você pode usar a propriedade has para validar se o existe o atributo dentro do json.

Segue:

    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");
                        }
                    }
                }
            }
      }
0

Não sei se poderá ser isso mas existe um método próprio do JSON para verificar se o valor está a NULL. O método é o isNull();

Por exemplo:

if(jsonObject.isNull("parentId")){
   jsonObject.put("parentId", 0);
}
1
  • Tentei utilizar o metodo, mas ele aponta que é incompativel e que é necessario uma variavel do tipo String. 20/03/2017 às 17:26

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .