【问题标题】:Why can't I access variable in my dictionary of JSON object?为什么我不能访问我的 JSON 对象字典中的变量?
【发布时间】:2019-04-26 15:35:59
【问题描述】:

我将逐层进入我的 JSON 对象以获取我需要的变量。我已经成功访问​​了项目之前部分中的变量,但是使用完全相同的方法它不会让我访问这个特定的变量。

我目前已经深入了大约 4 层,并成功抓取了以下等于变量“defaultsolo”的数据:

["placetop10": 2512, "minutesplayed": 4249, "lastmodified": 1556152357, "playersoutlived": 28024, "matchesplayed": 5552, "score": 140716, "kills": 39521, "placetop1": 1829, "placetop25": 3050]

下面的代码是我尝试访问变量“minutesplayed”。 defaultsolo 是 [String: Any] 类型,minutesplayed 说它是 String 类型。我的问题是它一直说 defaultSolo["minutesplayed"] 等于 "nil",但确实有一个值,如上所示。因此,它永远不会进入下面的逻辑。

if let soloPCResult = defaultSolo["minutesplayed"] as? String {
   //perform logic here with saved variable
}

【问题讨论】:

    标签: json swift string dictionary


    【解决方案1】:

    两个简单的 JSON 规则:

    1. 双引号中的所有内容都是String,甚至是"123""false"
    2. 带有小数位的数值为Double,其他为Int

    根据规则——没有双引号和小数位——它是

    if let soloPCResult = defaultSolo["minutesplayed"] as? Int {
       //perform logic here with saved variable
    }
    

    【讨论】:

      【解决方案2】:

      我认为是 Int 类型

      您是否尝试将此字段设为 Int?

      if let soloPCResult = defaultSolo["minutesplayed"] as? Int {
      

      【讨论】:

        【解决方案3】:

        minutesplayed 不是字符串。试试:

        if let soloPCResult = defaultSolo["minutesplayed"] as? Int {
           //perform logic here with saved variable
        }
        

        【讨论】:

          【解决方案4】:

          你的minutesplayed 看起来像Int,你应该这样做

          if let soloPCResult = defaultSolo["minutesplayed"] as? Int {
             //perform logic here with saved variable
          }
          

          【讨论】:

            【解决方案5】:

            可能是因为“minutesplayed”是Int 而不是String

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-01-09
              • 1970-01-01
              • 1970-01-01
              • 2012-12-14
              • 1970-01-01
              • 1970-01-01
              • 2020-07-27
              • 1970-01-01
              相关资源
              最近更新 更多