Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ara-ta3
Last active July 8, 2020 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ara-ta3/4a82457f9afe9198bbb64f71c6854ec2 to your computer and use it in GitHub Desktop.
Save ara-ta3/4a82457f9afe9198bbb64f71c6854ec2 to your computer and use it in GitHub Desktop.

swift json decode

Run

swift --version
Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53)
Target: x86_64-apple-darwin19.5.0

swift main.swift
A(a: main.B(b: "xxx", c: 2020-07-08 06:00:00 +0000, d: nil, e: [main.B.E.HOGE, main.B.E.FUGA, main.B.E.PIYO]))
A(a: main.B(b: "xxx", c: 2020-07-08 06:00:00 +0000, d: nil, e: [main.B.E.HOGE, main.B.E.FUGA, main.B.E.PIYO]))

Refference

import Foundation
let data = """
{
"a": {
"b": "xxx",
"c": "2020-07-08T15:00:00+09:00",
"d": null,
"e": [
"hoge",
"fuga",
"piyo"
]
}
}
""".data(using: .utf8)!
struct A: Decodable {
let a: B
}
struct B: Decodable {
let b: String
let c: Date
let d: Optional<Int>
let e: Array<E>
enum E: String, Decodable {
case HOGE = "hoge"
case FUGA = "fuga"
case PIYO = "piyo"
}
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let t1 = try decoder.decode(A.self, from: data)
print(t1)
decoder.dateDecodingStrategy = .formatted({
let f = DateFormatter()
f.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return f
}())
let t2 = try decoder.decode(A.self, from: data)
print(t2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment