Swift 4 + Alamofire 可解码 Json URL 格式

Swift 4 + Alamofire Decodable Json URL format

我有一个 JSON 格式,我无法使用 Alamofire 对其进行解码。

这是我的 json:

"data":[  
{  
    "id":37,
    "status":"A\u00e7\u0131k",
    "department":"Muhasebe",
    "title":"Y\u00f6netim Panelinden Deneme 4 - Mail Kontrol",
    "message":"<p>Y\u00f6netim Panelinden Deneme 4 - Mail Kontrol<br><\/p>",
    "file":null,
    "created_at":{  
        "date":"2018-01-13 01:59:49.000000",
        "timezone_type":3,
        "timezone":"UTC"
    },
    "replies":[  
        {  
            "id":6,
            "ticket_id":37,
            "admin_id":null,
            "user_id":8593,
            "message":"<p>test<\/p>",
            "file":"uploads\/tickets\/8593-P87wd8\/GFV6H5M94y5Pt27YAxZxHNRcVyFjD554i80og3xk.png",
            "created_at":"2018-01-18 11:16:55",
            "updated_at":"2018-01-18 11:16:55"
        }
    ]
},

这是我的 JSON 模型:

struct TeknikDestek : Decodable {
    var id: Int?
    var status: String?
    var title: String?
    var department: String?
    var message: String?

    var replies: [Replies]?
}

struct Replies: Decodable {
    var replyid: Int?
    var ticket_id: Int?
    var admin_id: Int?
    var user_id: Int?
    var message: String?
}

我将其命名为 Alamofire,但当我这样做时它不会返回 response.data。

        Alamofire.request("https://myurl.com.tr/api/tickets/\(userid)").responseJSON { (response) in

        switch response.result {
        case .success:
            if((response.result) != nil) {
                let jsonData = response.data
                print("jsonData: \(test)")
                do{
                self.allReplies = try JSONDecoder().decode([TeknikDestek].self, from: jsonData!)
                    print(self.allReplies)

                    for reply in self.allReplies {
                        print("Reply: \(reply)")
                    }
                }catch {
                    print("Error: \(error)")
                }
                self.view.dismissNavBarActivity()
            }
        case .failure(let error):
            print(error)
        }
    }

这是错误控制台:

我怎样才能让它发挥作用?我现在已经花了几个小时但没有成功。请帮我。非常感谢。

问题与 Alamofire 无关。只与JSONDecoder / Decodable

有关

根对象需要一个伞形结构,它是一个包含 data 键的字典,而不是数组。这就是错误消息的内容。

struct Root : Decodable {
    let data : [TeknikDestek]
}

然后解码Root

let root = try JSONDecoder().decode(Root.self, from: jsonData!)

并获得

的回复
self.allReplies = root.data.first?.replies // returns `nil` if data is empty

注意:强烈建议以单数形式命名数据结构(例如 Reply),在语义上您有一个 单数项集合