Search code examples
jsonswiftalamofire

What should I do next when I got the return data of Alamofire?


I use Alamofire to request the data from a website and then I print out the result in this way:

if let resultData = response.result.value {
    print(resultJson)
}

It appears in the console like this:

(
        {
        name = "Liu Bei";
        strength = 4;
        wisdom = 5;
    },
        {
        name = "Guan Yu";
        strength = 7;
        wisdom = 5;
    },
        {
        name = "Zhang Fei";
        strength = 7;
        wisdom = 3;
    }
)

Its type seems to be AnyObject, however what type can I parse it so that I can get the data such as name and strength of each character?


Solution

  • As vadian already stated in the comments.

    The JSON type is [[String:AnyObject]]

    if let resultArray = jsonResult as? [[String:AnyObject]]{
        for dictionary in resultArray{
            print(dictionary['name'])
            if let strength = dictionary['strength'] as? Int{
                print(strength)
            }
        }
    }
    

    This code will first check to see if the JSON is indeed of type [[String:AnyObject]]. It will than iterate over the array and print every name and strength in the array.