Search code examples
iosjsonswift3xcode8alamofire

Parse JSONArray contains JSONObjects Swift


hello i'm new to swift and I have responseJson from alamofire consist of jsonArray contain jsonObjects like this

[{"id":"1","name":"person1"},{"id":"2","name":"person2"}]

how i can parse it into array of this custom model

class Person {
  var name : String
  var id : String
}

i've done a much searching but can't find case identical to mine and i can't use Codable because i'm using xcode 8 and not able to upgrade my xcode version to 9 now

I'm getting the response like this

Alamofire.request(url).responseJSON{ response in
            if(response.result.isSuccess)
            {
                if let jsonarray = response.result.value as? [[String: Any]] 
                    {
                      //what to do here ?
                    }
            }
        }

Solution

  • if let jsonarray = response.result.value as? [[String: Any]]{
        //what to do here ?
        var persons:[Person] = []
        for userDictionary in jsonarray{
            guard let id = userDictionary["id"] as? String, let name = userDictionary["name"] as? String else { continue }
            persons.append(Person(id, name))
        }
        //Persons complete.
    }
    

    Use guard else for the required variables. If there are additional variables that could be optional, like var age:Int? in Person, you could do like this:

    for userDictionary in jsonarray{
        guard let id = userDictionary["id"] as? String, let name = userDictionary["name"] as? String else { continue }
        let age = userDictionary["age"] as? Int
        persons.append(Person(id, name, age))
    }