Swift 非常数值的可编码结构

Swift Codable struct for non constant value

我有一个 json,它的一部分不是常量,我不知道如何做 Codable 结构。 请参阅下面的示例代码:

fruits 部分不是常量,所以我不确定如何执行 Codable 结构。我试图在 SOF 上找到答案,但找不到“非常量 json Codable 结构”的任何答案。我可能没有搜索到正确的关键字。

谢谢。

这里是json的例子:

{
"success": true,
"username": "app",
"data": {
    "locations": {
        "asia": {
            "japan": {
                "store_count": 5
            },
            "korea": {
                "store_count": 3
            }
        }
    },
    "market": {
        "fruits": {
            "banana": {
                "price": 50.00,
                "count": 2
            },
            "apple": {
                "price": 444.00,
                "count": 16
            },
            "mango": {
                "price": 28.00,
                "count": 1
            },
            "peach": {
                "price": 50.00,
                "count": 2
            },
            "watermelon": {
                "price": 50.00,
                "count": 2
            },
            "blackberry": {
                "price": 57.00,
                "count": 2
            }
        }
    }
}

json

的结构
struct Markets: Codable {
    let success: Bool?
    let data: Data?

    struct Data: Codable {
        let locations: Locations
        let market: Market

        struct Locations: Codable {
            let asia: Asia

            struct Asia: Codable {
                let japan: Stores
                ler korea: 
            }

                struct Stores: Codable {
                    let store_count: Int
                }
        }

            struct Market: Codable {
               var fruits: Type

               struct Type: Codable {
                    // the fruits type are not constant.  
                   
               }
            }
        }
    }
}
import Foundation

// MARK: - Test
struct Test: Codable {
    let success: Bool
    let username: String
    let data: DataClass
}

// MARK: - DataClass
struct DataClass: Codable {
    let locations: Locations
    let market: Market
}

// MARK: - Locations
struct Locations: Codable {
    let asia: Asia
}

// MARK: - Asia
struct Asia: Codable {
    let japan, korea: Japan
}

// MARK: - Japan
struct Japan: Codable {
    let storeCount: Int

    enum CodingKeys: String, CodingKey {
        case storeCount = "store_count"
    }
}

// MARK: - Market
struct Market: Codable {
    let fruits: Fruits
}

// MARK: - Fruits
struct Fruits: Codable {
    let banana, apple, mango, peach: Apple
    let watermelon, blackberry: Apple
}

// MARK: - Apple
struct Apple: Codable {
    let price, count: Int
}

来自 https://app.quicktype.io/

只需输入您的 json 即可得到 class 或结构

定义一致的结构体:

struct FruitInfo: Codable {
    var price: Double
    var count: Int
}

并将它们映射到字符串:

var fruits: [String: FruitInfo]

如果你想要另一种类型的结构(例如将水果的名称嵌入到结构中),还有很多其他解决方案,但这是最简单的,不需要自定义 init.