web-dev-qa-db-ja.com

Codableに準拠するオブジェクトを辞書/配列で初期化する

主に私の使用例は、辞書を使用してオブジェクトを作成することです。

struct Person: Codable { let name: String }    
let dictionary = ["name": "Bob"]
let person = Person(from: dictionary)    

カスタム実装の記述を避け、できる限り効率的にしたいと考えています。

10

現時点で私が持っている最良のソリューションはこれですが、エンコード/デコードのオーバーヘッドがあります。

extension Decodable {
  init(from: Any) throws {
    let data = try JSONSerialization.data(withJSONObject: from, options: .prettyPrinted)
    let decoder = JSONDecoder()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:sszzz"
    decoder.dateDecodingStrategy = .formatted(dateFormatter)
    self = try decoder.decode(Self.self, from: data)
  }
}

質問の例に従うと、結果は次のようになります

let person = Person(from: dictionary)

他の方法に興味がある場合は、これが役立つかもしれません https://stackoverflow.com/a/46329055/1453346

28

に基づくChris Mitchelmore回答

細部

  • Xcodeバージョン10.3(10G8)、Swift 5

解決

import Foundation

extension Decodable {

    init(from value: Any,
         options: JSONSerialization.WritingOptions = [],
         decoder: JSONDecoder) throws {
        let data = try JSONSerialization.data(withJSONObject: value, options: options)
        self = try decoder.decode(Self.self, from: data)
    }

    init(from value: Any,
         options: JSONSerialization.WritingOptions = [],
         decoderSetupClosure: ((JSONDecoder) -> Void)? = nil) throws {
        let decoder = JSONDecoder()
        decoderSetupClosure?(decoder)
        try self.init(from: value, options: options, decoder: decoder)
    }

    init?(discardingAnErrorFrom value: Any,
          printError: Bool = false,
          options: JSONSerialization.WritingOptions = [],
          decoderSetupClosure: ((JSONDecoder) -> Void)? = nil) {
        do {
            try self.init(from: value, options: options, decoderSetupClosure: decoderSetupClosure)
        } catch {
            if printError { print("\(Self.self) decoding ERROR:\n\(error)") }
            return nil
        }
    }
}

使用法

struct Item: Decodable {
    let id: Int
    let name: String
    let isActive: Bool
    var date: Date
}

let dictionary = ["id": 1, "name": "Item", "is_active": false,
                  "date": "2019-08-06T06:55:00.000-04:00"] as [String : Any]
do {
    let item1 = try Item(from: dictionary) { decoder in
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        decoder.dateDecodingStrategy = .formatted(dateFormatter)
    }
    print(item1)
} catch {
    print("Error: \(error)")
}

print("\n========================")
let item2 = Item(discardingAnErrorFrom: dictionary)
print(String(describing: item2))

print("\n========================")
let item3 = Item(discardingAnErrorFrom: dictionary, printError: true)
print(String(describing: item3))

print("\n========================")
let item4 = Item(discardingAnErrorFrom: dictionary){ decoder in
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    decoder.dateDecodingStrategy = .formatted(dateFormatter)
}
print(String(describing: item4))

使用ログ

Item(id: 1, name: "Item", isActive: false, date: 2019-08-06 10:55:00 +0000)

========================
nil

========================
Item decoding ERROR:
keyNotFound(CodingKeys(stringValue: "isActive", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"isActive\", intValue: nil) (\"isActive\").", underlyingError: nil))
nil

========================
Optional(__lldb_expr_5.Item(id: 1, name: "Item", isActive: false, date: 2019-08-06 10:55:00 +0000))
1