14

私はこのような構造を持っています:

struct JSONModelSettings {
    let patientID : String
    let therapistID : String
    var isEnabled : Bool

    enum CodingKeys: String, CodingKey {
        case settings // The top level "settings" key
    }

    // The keys inside of the "settings" object
    enum SettingsKeys: String, CodingKey {
        case patientID = "patient_id"
        case therapistID = "therapist_id"
        case isEnabled = "is_therapy_forced"
    }
}

extension JSONModelSettings: Decodable {
    init(from decoder: Decoder) throws {

        // Extract the top-level values ("settings")
        let values = try decoder.container(keyedBy: CodingKeys.self)

        // Extract the settings object as a nested container
        let user = try values.nestedContainer(keyedBy: SettingsKeys.self, forKey: .settings)

        // Extract each property from the nested container
        patientID = try user.decode(String.self, forKey: .patientID)
        therapistID = try user.decode(String.self, forKey: .therapistID)
        isEnabled = try user.decode(Bool.self, forKey: .isEnabled)
    }
}

この形式の JSON (追加のラッパーなしで設定からキーをプルするために使用される構造):

{
  "settings": {
    "patient_id": "80864898",
    "therapist_id": "78920",
    "enabled": "1"
  }
}

質問は、「isEnabled」を Bool に変換する方法です (API から 1 または 0 を取得します)。応答を解析しようとすると、「Bool をデコードすると予想されますが、代わりに数字が見つかりました。」というエラーが表示されます。

4

5 に答える 5

14

そのような場合、私は通常、モデルを JSON データのように保持したいので、あなたの場合は Int. 計算されたプロパティをモデルに追加して、ブール値などに変換するよりも

struct Model {
   let enabled: Int
 
   var isEnabled: Bool {
       return enabled == 1
   }
}
于 2018-04-13T18:02:21.350 に答える
4

プロパティラッパー

Strings、Ints、Doubles またはBools を aにデコードするにはBool

@SomeKindOfBool次のようなブール値のプロパティの前に置くだけです。

@SomeKindOfBool public var someKey: Bool

デモ:

struct MyType: Decodable {
    @SomeKindOfBool public var someKey: Bool
}

let jsonData = """
[
 { "someKey": "true" },
 { "someKey": "yes" },
 { "someKey": "1" },

 { "someKey": 1 },

 { "someKey": "false" },
 { "someKey": "no" },
 { "someKey": "0" },

 { "someKey": 0 }
]
""".data(using: .utf8)!

let decodedJSON = try! JSONDecoder().decode([MyType].self, from: jsonData)

for decodedType in decodedJSON {
    print(decodedType.someKey)
}

この背後にある強力なPropertyWrapper実装:

@propertyWrapper
struct SomeKindOfBool: Decodable {
    var wrappedValue: Bool

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()

        //Handle String value
        if let stringValue = try? container.decode(String.self) {
            switch stringValue.lowercased() {
            case "false", "no", "0": wrappedValue = false
            case "true", "yes", "1": wrappedValue = true
            default: throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expect true/false, yes/no or 0/1 but`\(stringValue)` instead")
            }
        }

        //Handle Int value
        else if let intValue = try? container.decode(Int.self) {
            switch intValue {
            case 0: wrappedValue = false
            case 1: wrappedValue = true
            default: throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expect `0` or `1` but found `\(intValue)` instead")
            }
        }

        //Handle Int value
        else if let doubleValue = try? container.decode(Double.self) {
            switch doubleValue {
            case 0: wrappedValue = false
            case 1: wrappedValue = true
            default: throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expect `0` or `1` but found `\(doubleValue)` instead")
            }
        }

        else {
            wrappedValue = try container.decode(Bool.self)
        }
    }
}

オプションのものを実装する必要がある場合は、こちらの回答をご覧ください

于 2021-06-24T12:24:22.480 に答える
2

コードのいくつかの行を変更するだけで、としてデコードしてStringから に変換します。Bool

("0"は JSON 文字列であり、. としてデコードすることはできませんInt。)

struct JSONModelSettings {
    let patientID : String
    let therapistID : String
    var isEnabled : Bool

    enum CodingKeys: String, CodingKey {
        case settings // The top level "settings" key
    }

    // The keys inside of the "settings" object
    enum SettingsKeys: String, CodingKey {
        case patientID = "patient_id"
        case therapistID = "therapist_id"
        case isEnabled = "enabled"//### "is_therapy_forced"?
    }
}

extension JSONModelSettings: Decodable {
    init(from decoder: Decoder) throws {

        // Extract the top-level values ("settings")
        let values = try decoder.container(keyedBy: CodingKeys.self)

        // Extract the settings object as a nested container
        let user = try values.nestedContainer(keyedBy: SettingsKeys.self, forKey: .settings)

        // Extract each property from the nested container
        patientID = try user.decode(String.self, forKey: .patientID)
        therapistID = try user.decode(String.self, forKey: .therapistID)

        //### decode the value for "enabled" as String
        let enabledString = try user.decode(String.self, forKey: .isEnabled)
        //### You can throw type mismatching error when `enabledString` is neither "0" or "1"
        if enabledString != "0" && enabledString != "1" {
            throw DecodingError.typeMismatch(Bool.self, DecodingError.Context(codingPath: user.codingPath + [SettingsKeys.isEnabled], debugDescription: "value for \"enabled\" needs to be \"0\" or \"1\""))
        }
        //### and convert it to Bool
        isEnabled = enabledString != "0"
    }
}
于 2017-07-15T11:46:27.300 に答える