Swift 4 Codable; How to decode object with single root-level key

前端 未结 4 940
暖寄归人
暖寄归人 2020-12-02 13:21

I\'m using the Swift 4 Codable protocol with JSON data. My data is formatted such that there is a single key at the root level with an object value containing t

4条回答
  •  难免孤独
    2020-12-02 14:04

    You could decode using a dictionary: user combination then extract out the user object. e.g.

    struct User: Codable {
        let id: Int
        let username: String
    }
    
    let decoder = JSONDecoder()
    let userDictionary = try decoder.decode([String: User].self, from: jsonData)
    

提交回复
热议问题