我想用Alamofire解析JSON。我可以在项目中看到30个元素,但无法解析。错误是
无法将“字符串”类型的值转换为预期的参数类型“整数”
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
}
]
}
答案 0 :(得分:0)
您的响应是一个称为Dictionary的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)
}
}
}
答案 1 :(得分:0)
items
是一个包含多个 items 的数组。您必须使用循环。
并使用Swift本机类型,并且不注释编译器可以推断的类型
if let itemJson = response.result.value as? Dictionary<String,Any>,
let items = itemJson["items"] as? [[String:Any]] {
for item in items {
let name = item["name"] as? String
print(name ?? "n/a")
}
}
请考虑使用Decodable
。