0

关于从服务器传入的 Json 数据,dataString打印成功如下,

Debug;
Response: '[{"SSID": "ASUS_5G_2.4G_EXT", "RSSI": -66}, {"SSID": "Rattus_WiFi", "RSSI": -72}, {"SSID": "mgts371", "RSSI": -75}]'

我想将其转换为以下格式以使用基于我的 Struct 的对象。

let scannedNetworks = [["SSID": "ASUS_5G_2.4G_EXT", "RSSI": -66], ["SSID": "Rattus_WiFi", "RSSI": -72], ["SSID": "mgts371", "RSSI": -75]]

但是,当我print scannedNetworks出现以下错误时

ERROR:The data couldn’t be read because it isn’t in the correct format.

SWIFT代码;

static var scannedNetworks = [Network]()

static func URLrequest() {
     //...
     let task = URLSession.shared.dataTask(with: request) { data, response, error in
     guard let data = data, error == nil else {
         print(error?.localizedDescription ?? "No data")
         return
     }

     let dataString = String(data: data, encoding: .utf8) ?? ""
     print("Response: \(dataString)")
     do {
         scannedNetworks = try JSONDecoder().decode([Network].self, from: data)
         print(scannedNetworks)
     } catch {
         print(error.localizedDescription)
     }
 }
task.resume()
}

struct Network: Decodable {
var SSID: String
var RSSI: Int
init(SSID: String, RSSI: Int) {
    self.SSID = SSID
    self.RSSI = RSSI

}

private enum CodingKeys: String, CodingKey {
    case SSID
    case RSSI
}

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let SSID = try container.decode(String.self, forKey: .SSID)
    let RSSI = try container.decode(Int.self, forKey: .RSSI)
    self.init(SSID: SSID, RSSI: RSSI)
}
4

0 回答 0