How to use SwiftyJSON on nested JSON values

…衆ロ難τιáo~ 提交于 2019-12-01 18:19:40

问题


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.



来源:https://stackoverflow.com/questions/31715907/how-to-use-swiftyjson-on-nested-json-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!