Swift 2, how to get values ​​from the multi-stage JSON response

advertisements

I need to get values from a multistage JSON response.
For my login I get the following JSON data from my server:

{
"status": "...",
"payloadList": [
    {
    "type": "...",
    "authToken": "...",
    "user": {
        "id": ...,
        "firstName": "...",
        ...
        }
    }
]
}

to get the value firstName I tried the following:

do {
  let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]

  if let payload = (json["payloadList"] as? [AnyObject]){
     NSLog("Payload: %@", payload);
  }
  } catch let error as NSError {
     print("Failed to load: \(error.localizedDescription)")
}

Since it's multistage, I convert it into string: anyobject and not dictionary.
The payload looks now like this:

payload:  (
    {
    authToken = ...;
    type = ...;
    user =         {
        id = ...;
        firstName = ...;
        ...
        };
    }
    )

To get the first name I should now go through the anyobject. Unfortunately this doesn't work:

if let user = (payload["user"] as? [AnyObject]){
 NSLog("user: %@", user);
}

does someone know how to get the firstname out of it by go through the anyobject or does someone have an other solution from scratch by not using anyobject?
thanks a lot!


Your payload is an array of AnyObject objects. So you have to access to its objects by index. Try this variant:

for payloadItem in payload {
    if let user = payloadItem["user"] {
        print("user: %@", user);
    }
}