【问题标题】:Decode a dictionary in json using Swift 5 and Codable使用 Swift 5 和 Codable 解码 json 中的字典
【发布时间】:2021-07-10 10:22:21
【问题描述】:

我正在尝试使用 Swift 5.2 和 Codable 解码 JSON 中的数据(其中字典中的值对象不相似),任何这样做的建议都可以轻松扩展代码以在 json 中添加更多食物?

{
    "main courses": [
        {
            "date availabiliy": "June 12, 2017 1:23:31 PM",
            "price": 10.29,
            "name": "chicken_rice",
            "receipe": "page 16"
        },
        {
            "date availabiliy": "July 12, 2017 1:23:31 PM",
            "price": 12.29,
            "name": "beef_rice",
            "receipe": "page 5"
        },
        {
           "date availabiliy": "July 12, 2017 1:23:31 PM",
            "price": 14.49,
            "name": "California roll",
            "receipe": "page 25"
        }
    ],
    "desserts": [
        {
            "popularity": 75,
            "calory": "high",
            "name": "Avacado, Basil,and cream",
            "date availabiliy": "July 12, 2017 1:23:31 PM",
            "taste": "sweet",
        },
        {
           "popularity": 39,
            "calory": "med",
            "name": "ice cream",
            "date availabiliy": "July 22, 2017 1:23:31 PM",
            "taste": "sweet",
        },
    ],
}

谢谢! 凸轮

【问题讨论】:

    标签: json swift parsing codable


    【解决方案1】:

    这个模型是从https://app.quicktype.io/创建的

    import Foundation
    
    // MARK: - Response
    struct Response: Codable {
        let mainCourses: [MainCourse]
        let desserts: [Dessert]
    
        enum CodingKeys: String, CodingKey {
            case mainCourses = "main courses"
            case desserts = "desserts"
        }
    }
    
    // MARK: - Dessert
    struct Dessert: Codable {
        let popularity: Int
        let calory, name, dateAvailabiliy, taste: String
    
        enum CodingKeys: String, CodingKey {
            case popularity, calory, name
            case dateAvailabiliy = "date availabiliy"
            case taste
        }
    }
    
    // MARK: - MainCourse
    struct MainCourse: Codable {
        let dateAvailabiliy: String
        let price: Double
        let name, receipe: String
    
        enum CodingKeys: String, CodingKey {
            case dateAvailabiliy = "date availabiliy"
            case price, name, receipe
        }
    }
    

    像这样使用它

    let response = try? newJSONDecoder().decode(Response.self, from: jsonData)
    

    【讨论】:

    • @Cam 这个答案是用app.quicktype.io生成的,看看吧
    • 哦,你是对的。谢谢你告诉我埃里克
    • @EricAya 抱歉,我没有描述这一点,让我更新一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多