使用SwiftyJSON将JSON解析为结构

问题描述 投票:0回答:1

我有一个简单的结构来处理来自SwiftyJSON的数据解析

struct Threads{
    var threads:[ThreadDetail]
}

struct ThreadDetail {
    var title:String
    var username:String
    var prefix_id:Int
}

这里是API响应的示例

{
    "threads": [
        {
            "first_post_id": 258535,
            "prefix_id": 1,
            "thread_id": 50204,
            "title": "Testing board title",
            "user_id": 20959,
            "username": "test",
            "view_count": 247,
        }

现在这是我不知道怎么做的部分

        Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                for item in json["threads"].arrayValue {

                    //how should it be written here?

                }
            case .failure(let error):
                print(error)
            }
        }
    }
}
swift alamofire swifty-json
1个回答
0
投票

您可以按照我记得的SwiftyJSON进行操作:

Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { response in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            var models = [ThreadDetail]()
            for item in json["threads"].arrayValue {
                let model = ThreadDetail(title: item["title"].stringValue,
                                         username: item["username"].stringValue,
                                         prefix_id: item["prefix_id"].intValue)
                models.append(model)
            }
            // do whatever you need with models
        case .failure(let error):
            print(error)
        }
    }

但是实际上,就像Frankenstein所说的那样,解决问题的最佳方法就是使模型与Codable兼容。

© www.soinside.com 2019 - 2024. All rights reserved.