Get name index json Java Android Studio

Asked

Viewed 37 times

0

How can I get the index name 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 Dice that appear in json and check if it is empty, so I will create a method to validate a json and let you know which json or which ones are empty.

1 answer

1

Manage to find the solution, 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();
            }
        }

Browser other questions tagged

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