How to use SwiftyJSON on nested JSON values

2020-04-07 06:08发布

问题:

I'm calling a JSON API that has several nested values that I need to get. I'm using SwiftyJSON to make things a little cleaner. For the top level values, everything seems to be working fine, but on anything deeper, I'm getting the dreaded "nil when unwrapping optional value."

Here is how I'm making the API call with Alamofire:

Alamofire.request(APIRequests.Router.Nearby(self.page)).responseJSON(){
        (_,_,json,_) in
        println(json)
        if (json != nil){
            var jsonObj = JSON(json!)

            if let userArray = jsonObj ["results"].array {

                for userDict in userArray {
                        var username: String! = userDict["username"].string
                        var firstName: String! = userDict["firstName"].string
                        var profileImage: String! = userDict["userImages"]["profile"]["filename"].string
                        var characterName: String! = userDict["characters"]["characterName"].string

                        var user = User(username: username, profileImage: profileImage, firstName: firstName, characterName: characterName)

                        self.users.append(user)
                    }
                }

Here is a sample of the JSON:

{
  userInfo: {
     something: "abc",
     requestType: "GET"
  },
  results: [
    {
     username: "Jess",
     firstName: "Jessica",
     userImages: {
        profile: [
           {
            userImageID: "6",
            filename: "user-07.jpg"
           }
        ],
        cover: [
           {
            userImageID: "15",
            filename: "user-07.jpg"
           }
        ]
     },
     characters: [
         {
          userCharacterID: "8",
          characterName: "Amelia",
         }
     ]
}

For the top level keys username and firstName the debugger is showing the correct values, however, as soon as I dive a little deeper to get profileImage or characterName these are coming back as nil even though printing the json shows values for those keys.

What am I doing wrong? I'm just not seeing it.

Any thoughts would be helpful. Thank you.

回答1:

Try

var profileImage: String! = userDict["userImages"]["profile"][0]["filename"].string

var characterName: String! = userDict["characters"][0]["characterName"].string

and let us know what it gives.