ごまかすJSON

Format
C
Post date
2019-10-29 18:17
Publication Period
Unlimited
  1. import Foundation
  2. struct A: Decodable {
  3. let hoge: String
  4. private let shadowIsUse: IsUse
  5. var isUse: Bool { shadowIsUse.val }
  6. enum CodingKeys: String, CodingKey {
  7. case hoge
  8. case shadowIsUse = "isUse"
  9. }
  10. private struct IsUse: Decodable {
  11. let val: Bool
  12. init(from decoder: Decoder) throws {
  13. val = try Result<Bool, Error> {
  14. try decoder.singleValueContainer().decode(Bool.self)
  15. }
  16. .flatMapError { _ in
  17. Result { try decoder.singleValueContainer().decode(Int.self) != 0 }
  18. }
  19. .get()
  20. }
  21. }
  22. }
  23. let j1 = """
  24. {
  25. "isUse": false,
  26. "hoge": "hoge"
  27. }
  28. """
  29. let j2 = """
  30. {
  31. "isUse": 1,
  32. "hoge": "hoge"
  33. }
  34. """
  35. let decoder = JSONDecoder()
  36. print(try! decoder.decode(A.self, from: j1.data(using: .utf8)!))
  37. print(try! decoder.decode(A.self, from: j2.data(using: .utf8)!))
다운로드 Printable view

URL of this paste

Embed with JavaScript

Embed with iframe

Raw text