ごまかすJSON
- import Foundation
- struct A: Decodable {
- let hoge: String
- private let shadowIsUse: IsUse
- var isUse: Bool { shadowIsUse.val }
- enum CodingKeys: String, CodingKey {
- case hoge
- case shadowIsUse = "isUse"
- }
- private struct IsUse: Decodable {
- let val: Bool
- init(from decoder: Decoder) throws {
- val = try Result<Bool, Error> {
- try decoder.singleValueContainer().decode(Bool.self)
- }
- .flatMapError { _ in
- Result { try decoder.singleValueContainer().decode(Int.self) != 0 }
- }
- .get()
- }
- }
- }
- let j1 = """
- {
- "isUse": false,
- "hoge": "hoge"
- }
- """
- let j2 = """
- {
- "isUse": 1,
- "hoge": "hoge"
- }
- """
- let decoder = JSONDecoder()
- print(try! decoder.decode(A.self, from: j1.data(using: .utf8)!))
- print(try! decoder.decode(A.self, from: j2.data(using: .utf8)!))