Chris Allinson Chris Allinson - 2 months ago 10
iOS Question

Data > JSON - Swift3 - Convert & Parse

having one heck of a time handling the response I get from my API within a Swift3 app I'm building.

In the below screenshot, I am receiving Data from an httprequest using URLSession.shared, and passing it through to the handleSuccess method ... I am having issues simply converting to a JSON obj and accessing any of the key/values ...

trying to parse

...

func handleSuccess(jsonResponse: Data)
{
NSLog("Handle Success: \(jsonResponse)")

do
{
let json = try JSONSerialization.jsonObject(with: jsonResponse, options: .allowFragments)
NSLog("json: \(json)")

// I simply want to:
let firstName = json["firstName"]

Answer

try to parse your json into a dictionary first :

if let dict = json as? [String : AnyObject] {
  let firstName = dict["firstName"]
}