Reputation: 937
I'm trying to parse data from alamofire response. If i print all response it works good, but if i want to print specific parametr form JSON, for example "firstName" it is returning nil.
AF.request("http://localhost:5000/api/users").responseJSON(completionHandler: { (res) in
switch res.result {
case let .success(value):
let xjson : JSON = JSON(res.value)
print(xjson["firstName"].string)
case let .failure(error):
print(error)
}
})
No errors in console
Code below
AF.request("http://localhost:5000/api/users").responseJSON(completionHandler: { (res) in
switch res.result {
case let .success(value):
let xjson : JSON = JSON(res.value)
print(xjson)
print(xjson["firstName"].string)
case let .failure(error):
print(error)
}
})
returns
[
{
"dateOfBirth" : "1998-11-18T00:00:00.000Z",
"_id" : "5f6a29ed16444afd36e9fe15",
"email" : "[email protected]",
"__v" : 0,
"firstName" : "adam",
"lastName" : "kowalski",
"accountCreateDate" : "2020-09-22T16:44:29.692Z",
"userPassword" : "12345",
"userLogin" : "loginakowalski"
}
]
nil
Upvotes: 1
Views: 286
Reputation: 937
Thanks to everyone for your help. Below is the code that returns the correct value:
AF.request("http://localhost:5000/api/users").responseJSON(completionHandler: { (res) in
switch res.result {
case let .success(value):
let xjson : JSON = JSON(res.value)
if let firstUser = xjson.array?.first {
print(firstUser["firstName"].string!)
}
case let .failure(error):
print(error)
}
})
Upvotes: 1
Reputation: 15248
This xjson
is an Array
of JSON
(looks User) objects. So you need to access the array elements as below,
let xjson : JSON = JSON(res.value)
if let firstUser = xjson.array?.first {
print(firstUser["firstName"] as? String)
}
You can also put your JSON
response here and get the required data types and decoding code for free.
Upvotes: 2