使用Swift从Firebase中的子数据的子项获取密钥的特定值

时间:2016-12-06 21:12:19

标签: mongodb firebase nosql

你好我有这样的数据模型;

{
  "users" : {
    "User1" : {
      "flat1" : {
        "flataddress" : "adres1",
        "flatname" : "n1"
      },
      "flat2" : {
        "flataddress" : "adress2",
        "flatname" : "n2"
      }
    },
    "user2" : {
      "flat3" : {
        "flataddress" : "a3",
        "flatname" : "n1"
      },
      "flat4" : {
        "flataddress" : "a6",
        "flatname" : "a6"
      }
    }
  }
}

假设user1,user2,flat1,flat2是形成类似于" 3DSAZDSAPOYDZ"的一些ID。 第一个问题是我怎样才能得到所有平面的地址=" adres1"?

第二个问题是,如果我需要检索所有单位,则存在无法猜到的ID,如果我执行ref.getChild(" users"),则从快照中检索用户ID;

       {
  "users" : {
    "User1" : {
      "flat1" : {
        "flataddress" : "adres1",
        "flatname" : "n1"
      },
      "flat2" : {
        "flataddress" : "adress2",
        "flatname" : "n2"
      }
    },
    "user2" : {
      "flat3" : {
        "flataddress" : "a3",
        "flatname" : "n1"
      },
      "flat4" : {
        "flataddress" : "a6",
        "flatname" : "a6"
      }
    }
  }
}

已经包含用户ID,我想要这样的东西;

{

            flat1 =         {
                flataddress = adres1;
                flatname = n1;
            }
            flat2 =         {
                flataddress = adress2;
                flatname = n2;
            }


            flat3 =         {
                flataddress = a3;
                flatname = n1;
            }
            flat4 =         {
                flataddress = a6;
                flatname = a6;
            }

    }

提前致谢。

1 个答案:

答案 0 :(得分:0)

让我们调用您的主要回复 do { let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(paramsDict, options: NSJSONWritingOptions.PrettyPrinted) try jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String } catch { print("CAUGHT SOMETHING session token") } 。如果您想进入每个词典,您可以这样做:

Call can throw but is not marked with 'try'

由于JSON响应的结构方式,flatsDictArray将有两个字典,每个字典将有两个键,上面列出了JSON响应。因此,他们将按每个用户的单位进行分类。

因此,flatsDictArray将是:

jsonDict

如您所见,您可以逐步浏览每个级别的字典,以便按照我的方式查找键或值,因此如果您需要找到一个等于某个值的值,您可以采用相同的方式。

//make an empty array to put your dictionaries in
var flatsDictArray = [[String: AnyObject]]()

//first you have to unwrap each level of the dictionary response
guard let usersDict = jsonDict["users"] as? [String: AnyObject] else {
  //do something here if your json response is not what you expected
  //print usersDict below if you want to see what it looks like
  print(usersDict)
  return
}

//below we access the keys and values in the usersDict
//obj is the key, value is the value
for (obj, value) in usersDict {
  if let userFlats = value as? [String: AnyObject] {
    flatsDictArray.append(userFlats)
  }
}