SwiftyJson is convenient, but Swift table standard function Codable was also reasonably easy to use, so note
Just make the struct inherit Codable, convert the data of json, and then use JSONDecoder.decode. However, the type information defined in Codable and the form of json must be exactly the same. Therefore, if even one json key is missing, an error will occur.
var data = """
{
"name": "Bob",
"age": 20,
"sex": "male",
}
""".data(using: .utf8)!
struct User: Codable {
let name: String
let age: Int
}
let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: 1, age: 20)
Change the class of struct as follows and initialize it in the init function. Written in pure swift, it's easy to understand.
var data = """
{
"name": "Bob",
"age": 20,
}
""".data(using: .utf8)!
class User: Codable {
var name: String
var age: Int
var sex: String? //sex is not in json!
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? nil
self.age = try container.decodeIfPresent(Int.self, forKey: .age) ?? nil
self.sex = try container.decodeIfPresent(String.self, forKey: .sex) ?? nil
}
}
let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: "Bob", age: 20, sex: nil)
Codable isn't too bad compared to Swifty Json.
Recommended Posts