解码我的 json 的正确方法是什么

what's is the correct way to decode my json

对不起大家,我在这里绞尽脑汁。新手 swift 刚开始学习,无法解码以下已加星标

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

你能帮忙解决以下错误吗 - 我可以看到响应,只是无法解码它

“失败(SwiftClient.NetworkError.decodingError)”

提前感谢您的帮助

艾伦

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

("{\"data\":[{\"id\":\"1\",\"username\":\"johncase\",\"password\":\"a$tyFnx6.7yR/66QHDlySOf3PG9RIpusOEIGmDCRkOI9ZX888rkpy\"},{\"id\":\"2\",\"username\":\"johndoe\",\"password\":\"aiR3SdEjkVZ5w7/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()
        
        
    }
 *********************************************

根据您发布的示例:

("{\"data\":[{\"id\":\"1\",\"username\":\"johncase\",\"password\":\"a$tyFnx6.7yR/66QHDlySOf3PG9RIpusOEIGmDCRkOI9ZX888rkpy\"},{\"id\":\"2\",\"username\":\"johndoe\",\"password\":\"aiR3SdEjkVZ5w7/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)