Swift 4 + Alamofire可解码Json URL格式

时间:2018-01-19 08:10:32

标签: swift alamofire swift4 decodable

我有一个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)
        }
    }

这是错误控制台: Error console

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

1 个答案:

答案 0 :(得分:5)

该问题与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),从语义上讲,您有一个单数项集合