首页 > 解决方案 > 在另一个目录中解析 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。我该如何解析它?

标签: iosjsonswift

解决方案


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


推荐阅读