Search code examples
iosjsonnsurlsessiondatataskurlsessiondecodable

ios get decodable object parameter from json urlsession dataTask


From this reponse from URLSession dataTask, how do I transpose the data recieved:

response:  {"message":"login successful","data":{"id":15,"username":"Dummy2","password":"1234","email":"[email protected]","createdAt":"2017-12-23T19:52:49.547Z","updatedAt":"2017-12-23T19:52:49.547Z"}}

To this struct using the statement

struct User : Codable{
var id: String
var username: String
var password: String
var email: String
var createdAt: String
var updatedAt: String
}

let user = try decoder.decode(User.self, from: jsonData)   

It is of the type data but I need just the one data table, not both and I cannot subscript the received jsonData. I cannot get the right format for the from: parameter Im knew to using REST API and JSON and could really use the help. Thank you


Solution

  • You need a struct for the object with message and type to wrap this response, e.g. ResponseObject:

    struct User: Codable {
        let id: Int                  // NB: You must use `Int` not `String`
        let username: String
        let password: String
        let email: String
        let createdAt: Date          // NB: I'd use `Date`, not `String`
        let updatedAt: Date
    }
    
    func parserUser(from data: Data) -> User? {    
        struct ResponseObject: Decodable {
            let message: String
            let data: User?
        }
    
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
        formatter.locale = Locale(identifier: "en_US_POSIX")
    
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .formatted(formatter)
    
        let responseObject = try? decoder.decode(ResponseObject.self, from: data)
    
        return responseObject?.user
    }
    
    let user = parseUser(from: data)
    

    Note, this ResponseObject is not something that needs to be at a global scope, as it's only needed for the parsing of this particular request. Put it at whatever the narrowest scope that is best for your app (possibly just in the function.