解码 JSON 的正确方法是什么

问题描述 投票:0回答:1

刚刚学习 swift 的新手,无法解码下面加星标的内容。

成功接收请求后打印出来的响应。

您能帮忙解决以下错误吗?我可以看到响应但无法解码它。

“失败(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()
        
        
    }
 *********************************************
ios json swift decode
1个回答
1
投票

从您发布的示例中:

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

看起来

Data
有一个
Account
数组,而
Data
本身不是数组。像这样更改您的代码并尝试

struct MyData: Codable {
   let data: [Account]
}
struct Account: Codable {
    let id, username, password: String
}

...

let accounts = try? JSONDecoder().decode(MyData.self, from: data)
© www.soinside.com 2019 - 2024. All rights reserved.