-1

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.

Raon
  • 1,266
  • 3
  • 12
  • 25
  • It's not JSON, right? You can use `components(separatedBy:)` to get lines (with a new line `CharacterSet`), then again ` components(separatedBy:)` with the ":" separator, and then instantiate your object. – Larme Aug 28 '18 at 07:53

2 Answers2

0

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
     }
  }

}
Neel Bhasin
  • 749
  • 1
  • 7
  • 22
0

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)
Satish
  • 2,015
  • 1
  • 14
  • 22