Alamofire无法访问json响应的键

编程入门 行业动态 更新时间:2024-10-18 08:33:07
本文介绍了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("codewithchris/code/afsample.json").responseJSON { response in if let JSON = response.result.value { print(JSON) } }

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

The issue is that when I run this:

Alamofire.request("codewithchris/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("codewithchris/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("codewithchris/code/afsample.json").responseJSON { response in if let value = response.result.value { let json = JSON(value) print(json["firstkey"].stringValue) } } Alamofire.request("mmcalc/api").responseJSON { response in if let value = response.result.value { let json = JSON(value) print(json.arrayValue[0]["uniqueUsers"].stringValue) } }

更多推荐

Alamofire无法访问json响应的键

本文发布于:2023-11-26 20:46:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法访问   Alamofire   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!