Alamofire无法访问json响应的键 [英] Alamofire can't access keys of json response

查看:86
本文介绍了Alamofire无法访问json响应的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用Alamofire的新手,遇到了一个问题.我可以运行以下代码以打印出来自API端点的所有数据.

I'm new to using Alamofire and have encountered an issue. I'm able to run the following code to print out all the data from an API endpoint.

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

问题是,当我运行此命令时:

The issue is that when I run this:

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

我得到了错误:

任何"类型没有下标成员

Type 'Any' has no subscript members

我不知道为什么会发生此错误,似乎我正在正确访问数据.任何帮助都会很棒,谢谢!

I don't know why this error is happening, it seems as if I'm accessing the data correctly. Any help would be great, thanks!

我尝试过同时使用以下两种格式:

I have tried formatting it using both:

print(JSON ["firstkey"]作为字符串)

print(JSON["firstkey"] as String)

print(JSON ["firstkey"] as [String:Any]

print(JSON["firstkey"] as [String:Any]

但是它们仍然给出相同的错误.

but they still give the same error.

这是我端点上的JSON:

This is the JSON on my endpoint:

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

推荐答案

这真的很简单.您只需要强制转换(如!)您的JSON.所以将您的代码更改为此,它将起作用:

This is really simple. You just need to force cast (as!) your JSON. so change your code to this and it will work:

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

正如您在评论中所说,您正在使用SwiftyJSON包.示例代码如下:

Edit 1: As you said in comments that you are using SwiftyJSON package. Sample code is as follows:

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无法访问json响应的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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