简体   繁体   中英

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

How can i right a custom decorder for this.

NB: the keys 'firstname' 'rollnumber' are dynamic and are obtained from backend.

Parse like this, pass the response as Dict to the init method

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM