簡體   English   中英

Alamofire無法訪問JSON響應鍵

[英]Alamofire can't access keys of json response

我是使用Alamofire的新手,遇到了一個問題。 我可以運行以下代碼以打印出來自API端點的所有數據。

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON)
    }
}

問題是當我運行此命令時:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON["firstkey"])
    }
}

我收到錯誤:

類型“任何”沒有下標成員

我不知道為什么會發生此錯誤,似乎我正在正確訪問數據。 任何幫助將是巨大的,謝謝!

我試過使用兩種格式:

打印(JSON [“ firstkey”]為字符串)

print(JSON [“ firstkey”] as [String:Any]

但是它們仍然會給出相同的錯誤。

這是端點上的JSON:

{
    "firstkey":"it worked!",
    "secondkey":["item1", "item2", "item3"]
}

這真的很簡單。 您只需要強制轉換(如!)您的JSON。 所以將您的代碼更改為此,它將起作用:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        let json = JSON as! [String: Any]
        print(json["firstkey"])
    }
}

編輯1:正如您在評論中所說,您正在使用SwiftyJSON包。 示例代碼如下:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
        if let value = response.result.value {
            let json = JSON(value)
            print(json["firstkey"].stringValue)
        }
    }

Alamofire.request("https://mmcalc.com/api").responseJSON { response in
        if let value = response.result.value {
            let json = JSON(value)
            print(json.arrayValue[0]["uniqueUsers"].stringValue)
        }
    }

您正在嘗試通過獲取對象來獲取價值,請嘗試以下操作:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let result = response.result.value {
    let JSON = result as! NSDictionary
    print(JSON["firstkey"])
}
}

希望它能工作!

您應該添加! 在)之前的代碼末尾強制解開值

   Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
      if let JSON = response.result.value {
      let json = JSON as! [String: Any]
      print(json["firstkey"]!)
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM