我如何用alamofire解析JSON
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何用alamofire解析JSON相关的知识,希望对你有一定的参考价值。
我想用Alamofire解析JSON。我可以在项目中看到30个元素,但我无法解析。错误是
无法将'String'类型的值转换为预期的参数类型'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
}
]
}
答案
您的响应是一个称为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)
}
}
}
另一答案
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
。
以上是关于我如何用alamofire解析JSON的主要内容,如果未能解决你的问题,请参考以下文章
Alamofire 文件上传出现错误“JSON 文本未以数组或对象开头,并且允许未设置片段的选项”
Grails:request.JSON 是从哪里来的,我如何用 jQuery 的 .ajax() 或 .post() 把东西放在那里?