Reputation: 2397
I am trying to figure out how to access a nested JSON attributes, first element. Basically, my data looks like the following:
{
"message": "Error scenario",
"errors": {
"error_one": "error_one_message",
"error_two": "error_two"
}
}
Within my code, I am doing something like:
// it is an instance of HttpException
val message = JsonParser().parse(it.response().errorBody()?.string())
.asJsonOject["message"]
.asString
What should I change in my code to make the variable message
have the value error_one_message
Upvotes: 0
Views: 1397
Reputation: 1771
//the whole json object
val baseJsonResponse = JSONObject("JSON response")
//the error json object
val errorObject = baseJsonResponse.getJSONObject("error")
//get the string
val location = errorObject.getString("error_one")
edit: since you need the first element of the base object you will need to iterate through the keys to get the 1st key. In java it would be:
String keyForFirstJsonbject = errorObject.keySet().iterator().next();
im guessing in Kotlin it will be:
val keyForFirstJsonbject = errorObject.keys.elementAt(0)
then finish off with:
//get the string
val location = errorObject.getString(keyForFirstJsonbject)
Upvotes: 1
Reputation: 521
Try this?
val obj = JSONObject("ur Json string")
val error1 = obj.getJSONObject("errors").getString("error_one")
Upvotes: 1
Reputation: 201
I think this way will work
val message = JsonParser().parse(it.response().errorBody()?.string())
.asJsonObject["errors"]["error_one"]
.asString
but its better to use converting library like Gson here is GitHub Link
Upvotes: 2