Check if Jsonobject has a certain key

Asked

Viewed 502 times

0

this.token() is a String of the kind {"erro" : "Valor do erro"}.

But also, in case of success it may be: {"token" : "Valor do token"}

My goal with the code below is to find out if the first index of this JSONObject to be created will "erro" or "token" and I’m trying that way, but it looks like you’re testing whether the value for the index "erro" is null and not whether the error index itself exists or not.

JSONObject token = new JSONObject(this.token());

if (token.get("erro").equals(null))
    this.resposta.setText(token.getString("token"));
else
    this.resposta.setText(token.getString("erro"));

inserir a descrição da imagem aqui

1 answer

2


According to the documentation of JSONObject, the method get throws an exception (JSONException) if the key does not exist. And from what I understand, either JSON has the key "erro", or has the key "token", then if you don’t have the key "erro" and you try to access it with get, an exception will be made.

You might even wear a try/catch to capture the exception and know if the key exists or not, but to test if a key exists, you can simply use the method has, returning true or false (if the key exists or not):

JSONObject token = new JSONObject(this.token());

if (token.has("erro")) // tem erro
    this.resposta.setText(token.getString("erro"));
else // não tem erro, então pela sua descrição, deve ter a chave token
    this.resposta.setText(token.getString("token"));
  • 1

    That’s right! Thank you very, very much!

Browser other questions tagged

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