【问题标题】:Parsing my SWIFT Dictionary解析我的 SWIFT 字典
【发布时间】:2018-01-21 03:49:15
【问题描述】:

我正在查询一个 JSON 僵尸数据库,它将它们作为字典返回。我不知道如何使用 SWIFT 3 对其进行变异

这是查询::

func getZombieAttackGroupFromDatabase () {
        ref?.child("Attacker Group").child((self.userParty?.leadID)!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get data
            print("PULLING DATA")
            if let value = snapshot.value as? NSDictionary{

                // break data into an Array of Zombie Structs

          //      print(value)

                for zombieID in value.allKeys {
                    print(value[zombieID])

                    let thisZombieID = zombieID
                    let thisZombieGroup = value[zombieID]["Group"]
                }



            } else {

            }
            // ...
        }) { (error) in
            print(error.localizedDescription)
        }


}

这部分:让 thisZombieGroup = value[zombieID]["Group"] 未被识别。如何访问群组?如果我明白了,我可以修改其他组件。

这是回报:

{
    "-KrNSmv64Ia32g5nw1L9" =     {
        Group = 15;
        Health = 250;
        "Is Undead" = true;
        Location = 1;
        Number = 0;
    };
    "-KrNSmv64Ia32g5nw1LA" =     {
        Group = 11;
        Health = 250;
        "Is Undead" = true;
        Location = 5;
        Number = 1;
    };
    "-KrNSmv64Ia32g5nw1LB" =     {
        Group = 2;
        Health = 250;
        "Is Undead" = true;
        Location = 3;
        Number = 2;
    };
    "-KrNSmv776r9eO6t7CY0" =     {
        Group = 14;
        Health = 250;
        "Is Undead" = true;
        Location = 0;
        Number = 3;
    };
    "-KrNSmv776r9eO6t7CY1" =     {
        Group = 0;
        Health = 250;
        "Is Undead" = true;
        Location = 4;
        Number = 4;
    };
}

如您所见,每个 Struct 都有一个父级,该父级是一个自动生成的 ID。我不知道如何访问它。

如何访问第 1 项中的每个元素?我需要父自动密钥“-KrNSmv64Ia32g5nw1L9”和每个子值。

"-KrNSmv64Ia32g5nw1L9" =     {
        Group = 15;
        Health = 250;
        "Is Undead" = true;
        Location = 1;
        Number = 0; 

【问题讨论】:

  • 您是否在问如何将 JSON 解析为结构(并使用每个元素的根字符串作为每个结构的属性)?或者如何在事先不知道键的情况下访问字典结构?
  • 更新了我的查询
  • 制作打印(值[zombieID])。你会得到什么价值?
  • 每次运行都会得到不同的僵尸,所以数据不匹配,但代码是一样的:输出是 Optional({ Group = 6; Health = 250; "Is Undead " = true; Location = 5; Number = 1; }) Optional({ Group = 11; Health = 250; "Is Undead" = true; Location = 1; Number = 0; }) Optional({ Group = 1; Health = 250;“不死者”= true;位置 = 4;数量 = 3;}) 可选({ 组 = 10;健康 = 250;“不死者”= true;位置 = 2;数量 = 2;})跨度>
  • print(thisZombieID) 返回的正是我想要的。我只需要子级数据 ::: -KrNeL-emFB62OyXfBXy -KrNeL-emFB62OyXfBXx -KrNeL-emFB62OyXfBY- -KrNeL-dL_MwsXyTlp0- -KrNeL-emFB62OyXfBXz

标签: ios json swift dictionary firebase


【解决方案1】:

value 转换为正确的 Swift 字典,而不是 NSDictionary

if let value = snapshot.value as? [String:Any].

您只需要遍历字典的键,使用键值获取嵌入的字典,然后解析“僵尸数据”。

for key in value.keys {
    if let zombieData = value[key] as? [String:Any] {
        zombieData
        if let group = zombieData["Group"] as? Int, let health = zombieData["Health"] as? Int, let isUndead = zombieData["Is Undead"] as? Bool, let location = zombieData["Location"] as? Int, let number = zombieData["Number"] as? Int {
            //use the parsed data
        }
    }
}

【讨论】:

  • 我刚刚更新了帖子以包含查询。我不像你那样拥有它。关于如何修改我的闭包有什么想法吗?
  • 使用未解析的标识符 'jsonResponse' 我是否需要以某种方式启动 jsonResponse?我以前从未见过。
  • 我还必须将您的第一行修改为 value.allKeys 因为它是一个 NSDictionary
  • 我只是忘记将jsonResponse 更新为value,现在检查一下。正如您在我的回答中看到的那样,不要在 Swift 中使用 NSDictionary。将value 转换为 Swift 字典,正如您在我的回答中看到的那样。
  • 起初它什么也没做,所以我把所有的让从闭包中取出并删除了 if 语句。它现在为每个项目打印“nil”
【解决方案2】:

试试这个:

               for zombieID in value.allKeys {
                    print(value[zombieID])

                    let thisZombieID = zombieID
                    if let zombieValues = value[zombieID] as? [String:Any] {
                         let thisZombieGroup = zombieValues["Group"] as? Int
                    }
                }

【讨论】:

  • 为所有这个 ZombieGroup 打印 Nil
  • 当我这样做时,我添加了一个 print(thisZombieGroup) 并且所有值都为零
  • 您的值似乎是字符串,而不是字典。如果 letzombieValues = value[zombieID] as 试试这个? String { print(zombieValues) } 如果此代码将打印如下内容:"Group = 6; Health = 250; "Is Undead" = true; Location = 5; Number = 1;"所以这肯定是一个字符串
  • -KrNhJN_Wd-9hHfigioV [“健康”:250,“组”:21,“数字”:2,“位置”:5,“不死族”:true] -KrNhJN_Wd-9hHfigioU [”健康”:250,“组”:10,“编号”:1,“位置”:4,“不死族”:true] -KrNhJNZiTMwfMaARqPI [“健康”:250,“组”:23,“编号”:0 ,“位置”:3,“不死族”:true] -KrNhJN_Wd-9hHfigioX [“健康”:250,“组”:21,“数字”:4,“位置”:2,“不死族”:true] -KrNhJN_Wd-9hHfigioW [“健康”:250,“组”:21,“数字”:3,“位置”:0,“不死族”:true]
  • 有2个打印,第一个是ID,第二个是僵尸组。
【解决方案3】:

首先,非常感谢 Woof 和 David。这是你两个想法的结合,让它发挥作用。

    func getZombieAttackGroupFromDatabase () {
            ref?.child("Attacker Group").child((self.userParty?.leadID)!).observeSingleEvent(of: .value, with: { (snapshot) in
                // Get data
                print("PULLING DATA")
                if let value = snapshot.value as? [String:Any]{

                    // break data into an Array of Zombie Structs

                    for zombieID in value.keys {
                        let thisZombieID = zombieID
                        print(thisZombieID)

                        let zombieValues = value[zombieID] as? [String:Any]

                        let thisZombieGroup = zombieValues?["Group"] as! String
                        print(thisZombieGroup)

                    }
                } else {

                }
                // ...
            }) { (error) in
                print(error.localizedDescription)
            }
    }
}

【讨论】:

  • 这很好,但要小心解开zombieValues,因为如果数据有错误,那么你就会有致命错误。使用: if let thisZombieGroup =zombieValues?["Group"] as? String { } 或者为这种情况设置一个默认值: let thisZombieGroup = (zombieValues?["Group"] as?String) ?? ""
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2020-04-20
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
相关资源
最近更新 更多