ごまかすJSON

形式
C
投稿日時
2019-10-29 18:17
公開期間
無期限
  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)!))
ダウンロード 印刷用表示

このコピペの URL

JavaScript での埋め込み

iframe での埋め込み

元のテキスト