iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何在Swift 4中为JSON编写一个Decodable,其中键是动态的?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这样的 JSON.

我需要使用Swift 4在我的iOS应用程序中创建相应的Decodable结构.

{
    "cherry": {
        "filling": "cherries and love","goodWithIceCream": true,"madeBy": "my grandmother"
     },"odd": {
         "filling": "rocks,I think?","goodWithIceCream": false,"madeBy": "a child,maybe?"
     },"super-chocolate": {
         "flavor": "geRMAN chocolate with chocolate sHavings","forABirthday": false,"madeBy": "the charming bakery up the street"
     }
}

需要有关制作可解码结构的帮助.如何提及樱桃,奇数和超巧克力等未知密钥.

@H_450_14@解决方法
您需要的是在定义CodingKeys时发挥创意.让我们将响应称为FoodList和内部结构FoodDetail.您尚未定义FoodDetail的属性,因此我假设这些键都是可选的.

struct FoodDetail: Decodable {
    var name: String!
    var filling: String?
    var goodWithIceCream: Bool?
    var madeBy: String?
    var flavor: String?
    var forABirthday: Bool?

    enum CodingKeys: String,CodingKey {
        case filling,goodWithIceCream,madeBy,flavor,forABirthday
    }
}

struct FoodList: Decodable {
    var foodNames: [String]
    var foodDetails: [FoodDetail]

    // This is a dummy struct as we only use it to satisfy the container(keyedBy: ) function
    private struct CodingKeys: CodingKey {
        var intValue: Int?
        var stringvalue: String

        init?(intValue: int) { self.intValue = intValue; self.stringvalue = "" }
        init?(stringvalue: String) { self.stringvalue = stringvalue }
    }

    init(from decoder: Decoder) throws {
        self.foodNames = [String]()
        self.foodDetails = [FoodDetail]()

        let container = try decoder.container(keyedBy: CodingKeys.self)
        for key in container.allKeys {
            let foodName = key.stringvalue
            var foodDetail = try container.decode(FoodDetail.self,forKey: key)
            foodDetail.name = foodName

            self.foodNames.append(foodName)
            self.foodDetails.append(foodDetail)
        }
    }
}


// Usage
let list = try! JSONDecoder().decode(FoodList.self,from: jsonData)

大佬总结

以上是大佬教程为你收集整理的ios – 如何在Swift 4中为JSON编写一个Decodable,其中键是动态的?全部内容,希望文章能够帮你解决ios – 如何在Swift 4中为JSON编写一个Decodable,其中键是动态的?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。