Skip to content

Instantly share code, notes, and snippets.

@yunustek
Last active April 25, 2019 07:48
Show Gist options
  • Save yunustek/eb26819af73357fb6d36f308d020c1b7 to your computer and use it in GitHub Desktop.
Save yunustek/eb26819af73357fb6d36f308d020c1b7 to your computer and use it in GitHub Desktop.
Use Json Codable Inheritance Classes
import UIKit
open class BaseModel : Codable {
var deviceName: String?
private enum CodingKeys: String, CodingKey { case deviceName }
init() { }
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(deviceName, forKey: .deviceName)
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
deviceName = try container.decode(String.self, forKey: .deviceName)
}
}
final public class MyModel: BaseModel {
var username: String?
private enum CodingKeys: String, CodingKey { case username }
override init() { super.init() }
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
username = try container.decode(String.self, forKey: .username)
}
override public func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(username, forKey: .username)
}
}
// MARK: Encoder Example
let model = MyModel()
model.username = "1"
model.deviceName = "1"
let encoder = JSONEncoder()
let encodedJson = try encoder.encode(model)
let stringJson = String(data: encodedJson, encoding: .utf8)!
print("Encoded String: ", stringJson)
// MARK: Decoder Example
let jsonData = #"{"deviceName": "iPhone 7", "username":"Yunus TEK"}"#.data(using: .utf8)!
let decoder = JSONDecoder()
let superClass = try decoder.decode(MyModel.self, from: jsonData)
print("Decoded String: ", superClass.deviceName!, superClass.username!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment