0

I am getting following JSON string that I need to parse:

response => {
    "error":false,
    "uid":39,
    "user":{
        "name":"my username",
        "email":"[email protected]",
        "created_at":"2019-05-15 13:22:19",
        "updated_at":null,
        "imagen":null,
        "nombre":null,
        "apellidos":null,
        "nivel_usuario":null,
        "id_usuario":39,
        "unique_id":null,
        "verified":null,
        "cel_verificado":null,
        "tel":"123456789",
        "code_cel":null
    }
}

I need to get the values for the fields inside key user.

I am trying as follows, but not working:

String errorMsg = jObj.getString("error_msg");

Here I am getting an exception:

W/System.err: org.json.JSONException: No value for error_msg

and consequently, the following lines are not executed:

JSONObject jObj = new JSONObject(response);
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");

Log.d("RESPUESTA", "RESPUESTA email" + email);
1
  • There is no field named "error_msg" in your response. Maybe "error"? And the type of this field is boolean, not string. Commented May 15, 2019 at 23:49

2 Answers 2

4

That is because your JSON does not have a property named error_msg. It does have one named error, so perhaps that is what you are looking for (though it is a boolean, not a String, and it is at the top level, not inside the user object).

Sign up to request clarification or add additional context in comments.

Comments

0

Use optString() it will not give you exception

Also make sure what type of field is error_msg

Like if its a String use this

String error_msg= address.optString("error_msg")

for boolean use this

 boolean error_msg= address.optBoolean("error_msg")

Code snippet

JSONObject jObj = new JSONObject(response);
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");
String error_msg= address.optString("error_msg") //string type field use optBoolean for boolean
Log.d("RESPUESTA", "RESPUESTA email" + email);

More explanation here The difference between getString() and optString() in Json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.