Adrian
Adrian

Reputation: 315

JSON with Swift 3

I know there is already a lot of topics to do this but i tried all and im still getting an error.

Im doing this:

  let url = URL(string: "XXXXXXX")

        let jsonRequest = URLSession.shared.dataTask(with: url!){ (data, response, error) in

            if error != nil {

                print(error)

            } else {

                if let urlContent = data {

                    do {

                        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableArray

                        let responseMessage = (jsonResult[0] as AnyObject)["name"]! as? String

                        print(responseMessage)

                    } catch {

                        print("JSON Processing Failed")
                    }
                }
            }
        }
        jsonRequest.resume()

This is my Json:

[{
    "name": "Andrew",
    "id": "0",
}, {
    "name": "Jack",
    "id": "1",
}]

I can print the Andrew name without any problem but is there a better way to do this? All those cast don't seems right for me.

Upvotes: 0

Views: 214

Answers (1)

Abhra Dasgupta
Abhra Dasgupta

Reputation: 525

I would ideally prefer more swift specific type casting with lesser force unwraps if possible. This is how I would have preferred using it:

let url = URL(string: "xxxx")

let jsonRequest = URLSession.shared.dataTask(with: url!){ (data, response, error) in
    if error != nil {
        print(error)
    } else {
        guard let data = data else {
            return
        }
        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: AnyObject]] {
                let responseMessage = jsonResult[0]["name"] as? String
                print(responseMessage)
            }        
        } catch {
            print("JSON Processing Failed")
        }
    }
}
jsonRequest.resume()

Upvotes: 1

Related Questions