152

Swift 4 添加了新Codable协议。当我使用JSONDecoder它时,它似乎要求我的类的所有非可选属性Codable在 JSON 中都有键,否则它会引发错误。

让我的类的每个属性都是可选的似乎是不必要的麻烦,因为我真正想要的是使用 json 中的值或默认值。(我不希望该属性为零。)

有没有办法做到这一点?

class MyCodable: Codable {
    var name: String = "Default Appleseed"
}

func load(input: String) {
    do {
        if let data = input.data(using: .utf8) {
            let result = try JSONDecoder().decode(MyCodable.self, from: data)
            print("name: \(result.name)")
        }
    } catch  {
        print("error: \(error)")
        // `Error message: "Key not found when expecting non-optional type
        // String for coding key \"name\""`
    }
}

let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) // works, `name` is Jonny Applessed
load(input: badInput) // breaks, `name` required since property is non-optional
4

7 回答 7

168

您可以init(from decoder: Decoder)在您的类型中实现该方法,而不是使用默认实现:

class MyCodable: Codable {
    var name: String = "Default Appleseed"

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let name = try container.decodeIfPresent(String.self, forKey: .name) {
            self.name = name
        }
    }
}

您还可以创建name一个常量属性(如果您愿意):

class MyCodable: Codable {
    let name: String

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let name = try container.decodeIfPresent(String.self, forKey: .name) {
            self.name = name
        } else {
            self.name = "Default Appleseed"
        }
    }
}

或者

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
}

回复您的评论:使用自定义扩展

extension KeyedDecodingContainer {
    func decodeWrapper<T>(key: K, defaultValue: T) throws -> T
        where T : Decodable {
        return try decodeIfPresent(T.self, forKey: key) ?? defaultValue
    }
}

您可以将 init 方法实现为

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.name = try container.decodeWrapper(key: .name, defaultValue: "Default Appleseed")
}

但这并不比

    self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
于 2017-06-15T19:35:10.267 回答
56

如果未找到 JSON 键,您可以使用默认为所需值的计算属性。

class MyCodable: Codable {
    var name: String { return _name ?? "Default Appleseed" }
    var age: Int?

    // this is the property that gets actually decoded/encoded
    private var _name: String?

    enum CodingKeys: String, CodingKey {
        case _name = "name"
        case age
    }
}

如果你想让属性读写,你也可以实现setter:

var name: String {
    get { _name ?? "Default Appleseed" }
    set { _name = newValue }
}

这增加了一些额外的冗长,因为您需要声明另一个属性,并且需要添加CodingKeys枚举(如果还没有)。优点是您不需要编写自定义解码/编码代码,这在某些时候会变得乏味。

请注意,此解决方案仅在 JSON 键的值包含字符串或不存在时才有效。如果 JSON 可能具有其他形式的值(例如它的 int),那么您可以尝试此解决方案

于 2019-03-03T21:17:16.150 回答
28

我更喜欢的方法是使用所谓的 DTO - 数据传输对象。它是一个结构,符合 Codable 并表示所需的对象。

struct MyClassDTO: Codable {
    let items: [String]?
    let otherVar: Int?
}

然后,您只需使用该 DTO 初始化要在应用程序中使用的对象。

 class MyClass {
    let items: [String]
    var otherVar = 3
    init(_ dto: MyClassDTO) {
        items = dto.items ?? [String]()
        otherVar = dto.otherVar ?? 3
    }

    var dto: MyClassDTO {
        return MyClassDTO(items: items, otherVar: otherVar)
    }
}

这种方法也很好,因为您可以根据需要重命名和更改最终对象。与手动解码相比,它很清晰并且需要更少的代码。此外,通过这种方法,您可以将网络层与其他应用程序分开。

于 2019-07-29T19:13:40.610 回答
23

你可以实施。

struct Source : Codable {

    let id : String?
    let name : String?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "name"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decodeIfPresent(String.self, forKey: .id) ?? ""
        name = try values.decodeIfPresent(String.self, forKey: .name)
    }
}
于 2019-05-15T09:43:35.197 回答
10

我遇到了这个问题,正在寻找完全相同的东西。尽管我担心这里的解决方案将是唯一的选择,但我找到的答案并不是很令人满意。

就我而言,创建自定义解码器需要大量难以维护的样板文件,因此我一直在寻找其他答案。

我遇到了这篇文章,它展示了一种在简单情况下使用@propertyWrapper. 对我来说最重要的是它是可重用的,并且需要对现有代码进行最少的重构。

本文假设您希望缺少的布尔属性默认为 false 而不会失败,但也显示了其他不同的变体。您可以更详细地阅读它,但我将展示我为我的用例所做的工作。

就我而言,array如果缺少密钥,我想将其初始化为空。

因此,我声明了以下@propertyWrapper和其他扩展:

@propertyWrapper
struct DefaultEmptyArray<T:Codable> {
    var wrappedValue: [T] = []
}

//codable extension to encode/decode the wrapped value
extension DefaultEmptyArray: Codable {
    
    func encode(to encoder: Encoder) throws {
        try wrappedValue.encode(to: encoder)
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        wrappedValue = try container.decode([T].self)
    }
    
}

extension KeyedDecodingContainer {
    func decode<T:Decodable>(_ type: DefaultEmptyArray<T>.Type,
                forKey key: Key) throws -> DefaultEmptyArray<T> {
        try decodeIfPresent(type, forKey: key) ?? .init()
    }
}

这种方法的优点是您可以通过简单地添加@propertyWrapper属性来轻松克服现有代码中的问题。就我而言:

@DefaultEmptyArray var items: [String] = []

希望这可以帮助处理相同问题的人。


更新:

在继续调查此事的同时发布了这个答案后,我发现了另一篇文章,但最重要的是相应的库,其中包含一些常见的易于使用@propertyWrapper的此类案例:

https://github.com/marksands/BetterCodable

于 2020-07-26T17:51:55.477 回答
0

如果您认为编写自己的版本init(from decoder: Decoder)是压倒性的,我建议您实现一种方法,该方法将在将输入发送到解码器之前检查输入。这样,您将有一个地方可以检查字段是否缺失并设置自己的默认值。

例如:

final class CodableModel: Codable
{
    static func customDecode(_ obj: [String: Any]) -> CodableModel?
    {
        var validatedDict = obj
        let someField = validatedDict[CodingKeys.someField.stringValue] ?? false
        validatedDict[CodingKeys.someField.stringValue] = someField

        guard
            let data = try? JSONSerialization.data(withJSONObject: validatedDict, options: .prettyPrinted),
            let model = try? CodableModel.decoder.decode(CodableModel.self, from: data) else {
                return nil
        }

        return model
    }

    //your coding keys, properties, etc.
}

为了从 json 初始化一个对象,而不是:

do {
    let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    let model = try CodableModel.decoder.decode(CodableModel.self, from: data)                        
} catch {
    assertionFailure(error.localizedDescription)
}

初始化将如下所示:

if let vuvVideoFile = PublicVideoFile.customDecode($0) {
    videos.append(vuvVideoFile)
}

在这种特殊情况下,我更喜欢处理可选项,但如果您有不同的意见,您可以让您的 customDecode(:) 方法可抛出

于 2018-12-27T13:49:44.223 回答
0

如果您不想实现编码和解码方法,则默认值周围有一些肮脏的解决方案。

您可以将新字段声明为隐式展开的可选字段,并在解码后检查它是否为 nil 并设置默认值。

我仅使用 PropertyListEncoder 对此进行了测试,但我认为 JSONDecoder 的工作方式相同。

于 2019-03-03T19:36:12.513 回答