iPhone Guy iPhone Guy - 2 months ago 10
iOS Question

Convert JSON into Objects in Swift

I have a json response which is fetched from server and it should be parsed as dictionary and convert it to NSObjects in Swift. How can i do this.

func convertJSONToObjects(object:Dictionary<String,AnyObject>?) -> CommonResponse{
var response:CommonResponse;
if(object != nil){
response = CommonResponse()
var responseObject = object //It is dictionary

var responseHeader = object["responseHeader"] //error

response.status = responseHeader["status"] as Int //error
//response.status is Int
}
return response
}


var parsedJson = NSJSONSerialization.JSONObjectWithData(object as NSData, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as NSDictionary


calling function

convertJSONToObjects(parsedJson)

Answer

object is optional. You need some kind of unwrapping optional chaining, or optional bidding.

if let object = object {
    var responseHeader = object["responseHeader"]
}

or

var responseHeader = object!["responseHeader"]

or

if let responseHeader = object?["responseHeader"] {
    // ...
}

and so on.

Comments