Caspert Caspert - 1 year ago
545 0

I am trying to access nested JSON results using Alamofire and without SwiftyJson. I use below script to access an Array of objects, but this doesn't work for an object that contains other objects. What do I wrong and am I missing to get for example the value of key "name" in this example:

"name": "Tess"
"age": 25
"name": "Jason"
"age": 21


How to access nested JSON with Alamofire and Swift 3?

func getPersons() -> [Person] {
 // Array of persons
 var persons:[Person] = []

 // Get request Alamofire
 Alamofire.request(requestURL, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
    if let json = response.result.value as? Array<Any> {

        // Convert result to objects
        for field in json as? [NSDictionary] ?? [] {
            // Reference to person class
            let person = Person()

            // Add properties to a person object
   = field.object(forKey: "name") as? String
            person.age = field.object(forKey: "age") as? String

            // Add properties to person object


  return persons

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download