iosjsonswiftdecode

What's is the correct way to decode my JSON


New to swift just learning and can't decode below starred.

Its the response from print out after successfully receiving request.

Can you help please with below error? I can see response just can't decode it.

"failure(SwiftClient.NetworkError.decodingError)"

Response print out *****************

("{\"data\":[{\"id\":\"1\",\"username\":\"johncase\",\"password\":\"$2a$10$tyFnx6.7yR/66QHDlySOf3PG9RIpusOEIGmDCRkOI9ZX888rkpy\"},{\"id\":\"2\",\"username\":\"johndoe\",\"password\":\"$2a$10$3iR3SdEjkVZ5w7/666dZwOvwN7ohqd1L0jDt30k/nmSt0888VyLfe\"}]}")

struct MyData model**********
// MARK: - Welcome
struct MyData: Codable {
   let data: Account
}

// MARK: - Datum
struct Account: Codable {
    let id, username, password: String
}
************************

getallaccount function in web service ***********************
 func getAllAccounts(token: String, completion: @escaping (Result<[MyData], NetworkError>) -> Void) {
        
            guard let url = URL(string: "http://192.168.5.22:5000/users/getUpdated/") else {
            completion(.failure(.invalidURL))
            return
        }
        
        var request = URLRequest(url: url)
       
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue((token), forHTTPHeaderField: "gfg_token_header_key")
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data, error == nil else {
                completion(.failure(.noData))
                return
            }
           
         
        
           guard let accounts = try? JSONDecoder().decode([MyData].self, from: data) else {
           completion(.failure(.decodingError))
            return
           }
           
            completion(.success(accounts))
            
            
            
        }.resume()
        
        
    }
 *********************************************

Solution

  • From the example you posted:

    ("{\"data\":[{\"id\":\"1\",\"username\":\"johncase\",\"password\":\"$2a$10$tyFnx6.7yR/66QHDlySOf3PG9RIpusOEIGmDCRkOI9ZX888rkpy\"},{\"id\":\"2\",\"username\":\"johndoe\",\"password\":\"$2a$10$3iR3SdEjkVZ5w7/666dZwOvwN7ohqd1L0jDt30k/nmSt0888VyLfe\"}]}")
    

    Looks like Data has an array of Account while the Data itself is not an array. Change your code like this and try

    struct MyData: Codable {
       let data: [Account]
    }
    struct Account: Codable {
        let id, username, password: String
    }
    
    ...
    
    let accounts = try? JSONDecoder().decode(MyData.self, from: data)