3

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

这是错误控制台: 错误控制台

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

4

1 回答 1

7

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

于 2018-01-19T08:24:09.930 回答