Reputation: 5101
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);
Upvotes: 0
Views: 872
Reputation: 11457
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
Upvotes: 0
Reputation: 1006789
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).
Upvotes: 4