gpt4 book ai didi

json - 我如何使用 alamofire 解析 JSON

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

我想用 Alamofire 解析 JSON。我可以在项目中看到 30 个元素,但无法解析。错误是

Cannot convert value of type 'String' to expected argument type 'Int'

Alamofire.request("https://api.github.com/search/repositories?q=+language:swift&sort=stars&order=desc&page=%5Bdf6f765c265c02c1ef978f6ee3207407cf878f4d").responseJSON { response in

//print(response)

if let itemJson = response.result.value{
let itemObject : Dictionary = itemJson as! Dictionary<String,Any>
//print(itemObject)
let items : NSArray = itemObject["items"] as! NSArray
print(items)

let name : String = items["name"] as! String // Error is here
print(name)
}
}

{
"total_count": 551163,
"incomplete_results": false,
"items":
[
{
"id": 21700699,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTcwMDY5OQ==",
"name": "awesome-ios",
"full_name": "vsouza/awesome-ios",
"private": false,
"owner":
{
"login": "vsouza",
"id": 484656,
}
"forks": 5231,
"open_issues": 4,
"watchers": 31236,
"default_branch": "master",
"score": 1.0
},

{
"id": 21700699,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTcwMDY5OQ==",
"name": "awesome-ios",
"full_name": "vsouza/awesome-ios",
"private": false,

"owner":
{
"login": "vsouza",
"id": 484656,
}

"forks": 5231,
"open_issues": 4,
"watchers": 31236,
"default_branch": "master",
"score": 1.0
}
]
}

最佳答案

您的响应是一个称为字典的 JSON 对象,使用以下行

let itemObject = response.result.value as? [String : Any]

继续解析内部数组 items

if let array = itemObject?["items"] as? [[String : Any]] {
for dict in array {
guard
let id = dict["id"] as? Int,
let name = dict["name"] as? String,
let owner = dict["owner"] as? [String : Any],
let ownerId = owner["id"] as? Int

else {
print("Error parsing \(dict)")
continue
}

print(id, ownerId, name)
}
}

不是手动解析 JSON,而是使用 Codable 和 Alamofire 的 responseData,下面是一个例子

struct Item: Decodable {
let id: Int
let name: String
let owner: Owner
}
struct Owner: Decodable {
let id: Int
let login: String
}
struct PageData: Decodable {
let totalCount: Int
let incompleteResults: Bool
let items: [Item]

enum CodingKeys: String, CodingKey {
case totalCount = "total_count"
case incompleteResults = "incomplete_results"
case items
}
}

Alamofire.request("URL").responseData { response in
switch response.result {
case .failure(let error):
print(error)
case .success(let data):
do {
let pageData = try JSONDecoder().decode(PageData.self, from: data)
print(pageData, pageData.items.first?.name ?? "", pageData.items.first?.owner.id ?? 0)
} catch let error {
print(error)
}
}
}

关于json - 我如何使用 alamofire 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878627/

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