iPhone Guy iPhone Guy - 22 days ago 6x
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



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

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


var responseHeader = object!["responseHeader"]


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

and so on.