[英]Decoding SWIFT model class from text file
I have a model class我有一个模型类
class User{
var name:String
var number:Int
}
i have the details of this downloaded as a text file with format我有这个下载的详细信息作为格式的文本文件
firstname:John
rollnumber:234
5 5
How can i right a custom decorder for this.我怎样才能为此正确使用自定义装饰器。
NB: the keys 'firstname' 'rollnumber' are dynamic and are obtained from backend.注意:键 'firstname' 'rollnumber' 是动态的,是从后端获得的。
Parse like this, pass the response as Dict
to the init
method像这样解析,将响应作为
Dict
传递给init
方法
class User{
var name:String?
var number:Int?
init(With dict:[String:Any]){
if let value = dict["firstname"] as? String{
name = value
}
if let value = dict["rollnumber"] as? Int{
number = value
}
}
}
Would be something like this:会是这样的:
struct User: Decodable {
let name: String
let number: Int
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: UserKeys.self)
name = try container.decode(String.self, forKey: .name)
number = try container.decode(Int.self, forKey: .number)
}
private enum UserKeys: String, CodingKey {
case name = "firstname"
case number = "rollnumber"
}
static getUser(jsonData: Data) -> User? {
do {
let user = try JSONDecoder().decode(User.self, from:jsonData)
return user
} catch {
return nil
}
}
}
And get user:并获取用户:
User.getUser(jsonData: data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.