简体   繁体   中英

Swift 2, how to get values from multistage JSON response

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);
    }
}

user is not an array but dictionary. Try the following, it should work:

if let user = (payload["user"] as? [String:AnyObject]) {
    print("\(user)")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM