ios - 在另一个目录中解析 JSON 目录
问题描述
Alamofire.request("https://example.com/stories.php", method: .post, parameters: parameters).validate().responseJSON { response in
switch response.result {
case .success:
if let json = response.result.value {
let json2 = JSON(json)
for (_, subJSON): (String, JSON) in json2[0]["stories"] {
if let arr = subJSON["user"].dictionary {
let title = arr["name"]?.string
let id = arr["id"]?.int
let photo = arr["picture"]?.string
let rel1 = InboxStories(title: title!, storyID: id!, photo:photo!)
cell.arrayOfRels.append(rel1)
}
}
cell.getStoryDel()
}
case .failure(_):
print("hata")
}
}
JSON 输出
[{
"stories": [{
"id": "s1",
"last_updated": "1582543824",
"user": {
"id": "2",
"name": "testuser",
"picture": "https:\/\/example.com\/ios\/images\/profile_pic\/116534.jpg"
},
"snaps_count": "1",
"snaps": [{
"id": "c1",
"mime_type": "image",
"url": "chttps:\/\/example.com\/ios\/stories\/image\/3434.jpg",
"last_updated": "1582543824"
}]
}],
"count": 1
}]
我正在尝试获取故事的用户密钥。
它在我的代码中返回 nil。我该如何解析它?
解决方案
stories
也是一个数组,请注意[]
给字典命名很混乱arr
if let stories = json2.array?.first?["stories"].array {
for story in stories {
if let dict = story["user"].dictionary {
let title = dict["name"]!.stringValue
let id = dict["id"]!.stringValue
let photo = dict["picture"]!.stringValue
let rel1 = InboxStories(title: title, storyID: id, photo:photo)
cell.arrayOfRels.append(rel1)
}
}
}
并考虑使用Decodable
. 它是内置的,比它更舒适SwiftyJSON
推荐阅读
- mysql - 给出日期的时间
- laravel - 当输入是数组时,Laravel 中的“存在”验证问题
- python - 如何获取不在 Discord 公会中的用户的用户名?
- linq - WhenAll 结果异步中的 Distinct/GroupBy
- c++ - 防止编译器分离函数的指令
- odoo - AssertionError: Element odoo has extra content: 记录,第 3 行 - - - Odoo13
- c# - 即使数据发生变化,使用实时数据库也能获得相同的结果
- ios - 将 IndexPath 行值传递给委托函数而不是 Sender.tag 以删除图像项 CollectionView Swift
- video-streaming - libVLC 在 Visual Studio 中显示绿屏(但相同的流在 VLC 中很好)
- python-3.x - 从 CRS 创建 Transformer 时出错:源椭球体和目标椭球体不属于同一个天体