如何为嵌套 JSON 简化 Swift Codable 结构?

How to simplify Swift Codable Struct for nested JSON?

我有一个json这样的。

{
  "connectType": "CALL",
  "connectFrequency": "WEEKLY",
  "status": {
    "status": "On"
  }
}

我正在尝试使用 Swift 中的 Codable 来解析它。我可以像下面这样想:

struct Preference : Codable {
    let connectFrequency : String?
    let connectType : String?
    let status : PreferenceStatus?
}

struct PreferenceStatus : Codable {
    let status : String?
}

现在当我必须检查 status on/off 值时,我将不得不像 obj.status?.status 那样去检查。我理想中想要的是删除嵌套,因为它在 PreferenceStatus.

中只有一个值

有没有办法像下面这样使用相同的方式定义我的模型 json :

struct Preference : Codable {
    let connectFrequency : String?
    let connectType : String?
    let status : String?
}

我是 Codable 范例的新手。请协助。谢谢。

要展平结构,您必须手动解码 JSON status 可以解码为枚举。 connectFrequencyconnectType 似乎也是枚举。

let jsonString = """
{
  "connectType": "CALL",
  "connectFrequency": "WEEKLY",
  "status": {
    "status": "On"
  }
}
"""

enum Frequency : String, Decodable {
   case hourly = "HOURLY", weekly = "WEEKLY"
}

enum Status : String, Decodable {
   case off = "Off", on = "On"
}

struct Preference : Decodable {
    let connectFrequency : Frequency
    let connectType : String
    let status : Status
    
    private enum CodingKeys : String, CodingKey { case connectFrequency, connectType, status }
    
    init(from decoder : Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        connectFrequency = try container.decode(Frequency.self, forKey: .connectFrequency)
        connectType = try container.decode(String.self, forKey: .connectType)
        let nestedContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .status)
        status = try nestedContainer.decode(Status.self, forKey: .status)
    }
}

let data = Data(jsonString.utf8)

do {
    let result = try JSONDecoder().decode(Preference.self, from: data)
    print(result)
} catch {
    print(error)
}