Get name index json Java Android Studio

0

How can I get the index names of a JSON object in Java in Android Studio.

Code:

JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("nome", "");
            jsonObject.put("sobrenome", "asdasd");
            jsonObject.put("nomeCompleto", "Renato Vieira de Souza");
        } catch (JSONException e) {
            e.printStackTrace();
        }


        for(int i=0; i < jsonObject.length(); i++){
            try {
                if(VERIFICAR AQUI SE CADA INDICE DO ARRAY É MENOR QUE 1){
                    Recursos.toastLento(getApplicationContext(), "nome vazio");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

My need is to detect any index that appears in json and check if it is empty, so I will create a method to validate a json and tell which json or which ones are empty.

    
asked by anonymous 13.12.2018 / 19:57

1 answer

1

Finding the solution is as follows:

JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("nome", "");
            jsonObject.put("sobrenome", "");
            jsonObject.put("nomeCompleto", "Renato Vieira de Souza");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Iterator<?> keys = jsonObject.keys();

        while(keys.hasNext()){
            String key = (String)keys.next();
            try {
                if(jsonObject.getString(key).length() < 1){
                    AlertDialog alertDialog = new AlertDialog.Builder(CadastroClienteActivity.this).create();
                    alertDialog.setTitle("Teste");
                    alertDialog.setMessage(key + "Vazia");
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "teste", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    alertDialog.show();
                    //Recursos.toastLento(getApplicationContext(), key + " Vazia");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
13.12.2018 / 20:30