Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting JSON data in Swift

Tags:

json

swift

I'm getting some JSON data from a server that I've parsed to a dictionary. Now I want to get the data from the dictionary and cast it as different types but I get some errors.

I've tried

let manager = AFHTTPRequestOperationManager()
manager.requestSerializer = AFJSONRequestSerializer()
manager.GET(
    "http://localhost/example/jsonpage",
    parameters: nil,
    success: { (operation: AFHTTPRequestOperation!,
        responseObject: AnyObject!) in

        if let data = responseObject as? Dictionary<String, AnyObject> {
            let id = data["id"] as? Int
            let persons = data["persons"] as? Dictionary<String, AnyObject>
        }


    },
    failure: { (operation: AFHTTPRequestOperation!,
        error: NSError!) in
        println("Error: " + error.localizedDescription)
    }
)

These gives me an error:

let id = data["id"] as? Int
let persons = data["persons"] as? Dictionary<String, AnyObject>

Error: Could not find an overload for 'subscript' that accepts the supplied arguments

like image 531
Oskar Persson Avatar asked Dec 19 '25 23:12

Oskar Persson


1 Answers

The responseObject is of Type NSDictionary, and the supported JSON value Types are NSDictionary, NSArray, NSString, NSNumber. Casting to Dictionary does not cast its values to the correct Type. You have to cast the values individually.

if let nsid: NSNumber = data["id"] as? NSNumber {
    var id = Int(nsid)
}
like image 101
Santosh Avatar answered Dec 22 '25 15:12

Santosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!