gpt4 book ai didi

json - 当我遍历 "Type ' 结果时,错误 'Sequence"Any' does not conform to protocol 'JSON' 是什么意思?

转载 作者:行者123 更新时间:2023-11-28 07:29:18 25 4
gpt4 key购买 nike

我目前正在学习 Swift。我正在制作一个可以解析网站历史数据并在图 TableView 中显示这些数据的应用程序。我一直在使用 Alamofire 解析网页中的 JSON 数据,并尝试遍历此结果并尝试将这些数据存储在数组中。但是,当我遍历 JSON 结果时遇到问题。它说:

"Type 'Any' does not conform to protocol 'Sequence".

这是我写的函数:

func getHistoryData(url: String) {
Alamofire.request(url).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result

if let json = response.result.value {
print("JSON: \(json)") // serialized json response
for item in json { ***(The error happens here)***

}
}

if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
}

以下是来自网页的响应示例:

{
"average": 4088.82,
"time": "2019-03-30 15:46:00"
},
{
"average": 4095.07,
"time": "2019-03-30 15:45:00"
},
{
"average": 4094.14,
"time": "2019-03-30 15:44:00"
},
{
"average": 4095.64,
"time": "2019-03-30 15:43:00"
},
{
"average": 4095.69,
"time": "2019-03-30 15:42:00"

如何获取所有“平均值”并将它们存储在数组中?

最佳答案

这实际上取决于您要获得的序列类型,但在大多数情况下这应该可行。

改变

for item in json 

var jsonparsed = JSON(json);
for item in jsonparsed.array

根据您的 json,它看起来像这样:

var averages : [Float] = [];

if let json = response.result.value {
print("JSON: \(json)") // serialized json response
var jsonparsed = JSON(json);
for item in jsonparsed.array {
if let average = item["average"].float {
averages.append(average);
}
}
}

// do something with the `averages` array.

关于json - 当我遍历 "Type ' 结果时,错误 'Sequence"Any' does not conform to protocol 'JSON' 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55433042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com