extension Encodable {
subscript(key: String) -> Any? {
return dictionary[key]
}
var jsonData: Data? {
return try? JSONEncoder().encode(self)
}
var dictionary: [String: Any] {
guard let data = jsonData else {return [:]}
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
}
var jsonStr: String? {
guard let data = jsonData else {return nil}
return String(data: data, encoding: .utf8)
}
}
extension Decodable {
static func getModel(data: Data) -> Self? {
return try? JSONDecoder().decode(self, from: data)
}
static func getModel(jsonStr: String) -> Self? {
guard let data = jsonStr.data(using: .utf8) else {return nil}
return try? JSONDecoder().decode(self, from: data)
}
}
test:
struct Teacher: Codable {
let name: String
let age: Int
}
struct Test: Codable {
let name: String
let age: Int
let height: Double
let teacher: Teacher
}
let test = Test(name: "aaa", age: 11, height: 120, teacher: Teacher(name: "bbb", age: 30))
test.jsonStr //"{\"age\":11,\"name\":\"aaa\",\"height\":120,\"teacher\":{\"name\":\"bbb\",\"age\":30}}"
test.dictionary //["age":11,"name":"aaa","height":120,"teacher":["name":"bbb","age":30]]
test.jsonData //
let jsonStr = "{\"name\":\"ccc\",\"age\":20,\"height\":170,\"teacher\":{\"name\":\"ddd\",\"age\":40}}"
let jsonData = jsonStr.data(using: .utf8)!
if let test2 = Test.getModel(data: jsonData) {
test2.name //"ccc"
test2.age //20
test2.height //170
test2.teacher.name //"ddd"
test2.teacher.age //40
}
if let test3 = Test.getModel(jsonStr: jsonStr) {
test3.name //"ccc"
test3.age //20
test3.height //170
test3.teacher.name //"ddd"
test3.teacher.age //40
}
Demo:
Demo