In my swift
app I'm using SwiftyJSON
and Alamofire
.
I have a json that comes back from my backend to the application:
{
"responses" : [
{
"labelAnnotations" : [
{
"mid" : "\/m\/01yrx",
"score" : 0.8735667499999999,
"description" : "cat"
},
{
"mid" : "\/m\/0l7_8",
"score" : 0.7697883,
"description" : "floor"
},
{
"mid" : "\/m\/01c34b",
"score" : 0.7577944,
"description" : "flooring"
},
{
"mid" : "\/m\/03f6tq",
"score" : 0.52875614,
"description" : "living room"
},
{
"mid" : "\/m\/01vq3",
"score" : 0.52516687,
"description" : "christmas"
}
]
}
]
}
I want to construct an array of Strings
that contains each description mentioned above.
I tried to parse it with code:
{
case .success:
print("sukces")
if let jsonData = response.result.value {
let data = JSON(jsonData)
print(data)
if let responseData = data["responses"] as? JSON{
if let responseData2 = responseData["labelAnnotations"] as? JSON{
for userObject in responseData2 {
print(userObject["description"])
}
}
}
}
case .failure(let error):
print("fail")
print(error)
}
}
but line print(userObject)
returns empty String. How can I display each description? As soon as I can print it in the console I will add it to my array.
Checking if dictionary values are of JSON
type seems to be the problem here because all SwiftyJSON
does is to save you to trouble of doing type checking using as? ...
.
I am not familiar with the library but I think all you have to do is:
(Assuming response.result.value
returns a dictionary since you've used .responseJSON
method like Alamofire.request(...).responseJSON(...)
otherwise you'll have to do JSON(data: $0.data)
if you've called .response(...)
instead.)
Alamofire.request(...).responseJSON { response in
if let dictionary = response.result.value {
let JSONData = JSON(dictionary)
let userObjects = JSONData["responses"][0]["labelAnnotations"].arrayValue.map(
{ $0["description"].stringValue }
)
}
}