dynamic dictionary name decoder json

后端 未结 1 1776
萌比男神i
萌比男神i 2021-01-23 08:15

Swift 4. I\'m in a very similar situation than Using Codable on a dynamic type/object but for me the changing variable is the name of the dictionary and not the keys inside. It

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 08:47

    If you already know all the keys in the inner JSON, use a struct to take advantage of static typing. Assuming that there's only 1 key on the top level in your JSON (your customName key):

    struct MyModel: Decodable {
        struct InnerModel: Decodable {
            var constantKey1: Double
            var constantKey2: Double
        }
    
        var customName: InnerModel
    
        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: GenericCodingKeys.self)
    
            // Assume that there's only 1 key at the top level in the JSON
            if let key = container.allKeys.first {
                customName = try container.decode(InnerModel.self, forKey: key)
            } else {
                throw NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "JSON is empty"])
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题