如何使用SwiftyJSON嵌套的JSON值 [英] How to use SwiftyJSON on nested JSON values

查看:119
本文介绍了如何使用SwiftyJSON嵌套的JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话一个JSON API,它有我需要得到多个嵌套值。我使用SwiftyJSON做事情有点清洁。对于顶层的价值观,一切似乎都做工精细,但更深层次的东西,我得到了可怕的展开可选值时零。

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."

下面是我正在做与Alamofire API调用:

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

下面是JSON的示例:

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",
         }
     ]
}

有关顶级键用户名的firstName 调试器显示正确的价值观,但是,只要我下潜得更深一些,以获得 profileImage characterName 这些都回来了作为零,即使打印的json显示了值这些密钥。

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.

推荐答案

尝试

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

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

和让我们知道它给了。

这篇关于如何使用SwiftyJSON嵌套的JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆