Skip to content

Instantly share code, notes, and snippets.

@wotjd
Created September 6, 2019 15:09
Show Gist options
  • Save wotjd/39626f42b7cd74190748b88b8391f0ee to your computer and use it in GitHub Desktop.
Save wotjd/39626f42b7cd74190748b88b8391f0ee to your computer and use it in GitHub Desktop.
easily convert json data to model object
import Foundation
protocol Receivable {
init?(from: Data)
}
extension Receivable where Self: Decodable {
init?(from jsonData: Data) {
guard let decoded = try? JSONDecoder().decode(Self.self, from: jsonData) else { return nil }
self = decoded
}
}
extension Array where Element: Receivable & Decodable {
init?(from jsonData: Data) {
guard let decoded = try? JSONDecoder().decode(Array<Element>.self, from: jsonData) else { return nil }
self = decoded
}
}
struct TestObject2: Codable, Receivable {
let id: String
let pass: String
}
// TEST
let jsonData = "{\"id\":\"hi\", \"pass\":\"omg\"}".data(using: .utf8)!
// try! JSONEncoder().encode(TestObject2(id: "hi", pass: "omg"))
print(TestObject2(from: jsonData))
let jsonArrayData = "[{\"id\":\"hi\", \"pass\":\"omg\"}, {\"id\":\"bye\", \"pass\":\"good\"}]".data(using: .utf8)!
//try! JSONEncoder().encode([TestObject2(id: "hi", pass: "omg"), TestObject2(id: "hi2", pass: "omg!!!")])
print([TestObject2](from: jsonArrayData))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment