我對 Swift 很陌生,所以如果這是一個愚蠢的問題,請原諒我如何處理這種型別的資料模型回應,回應形式如下:
{
"id" = 1;
count = "";
data = "[{"key":"value","key":"value".......}]";
message = SUCCESS;
"response_code" = 1;
}
AlamofireRequest 獲取回應并列印它,但是當使用 responseDecodable 時,沒有任何反應,Alamofire 請求的代碼如下:
let request = AF.request(urlString!,method: .get)
request.responseJSON { (data) in
print(data)
}
request.responseDecodable(of: Test.self) { (response) in
guard let getData = response.value else {return}
print(getData.all[0].firstName) //Nothing prints
}
這就是資料模型的樣子:
struct Test: Decodable {
let firstName: String
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
//firstname is inside data of json
}
}
struct Getdata: Decodable {
let all : [Test]
enum CodingKeys: String, CodingKey {
case all = "data"
}
}
想要訪問資料中的值并列印它。請對此有所了解!
uj5u.com熱心網友回復:
試圖同時解決上述問題和評論,第一件事是獲取一些有效的 JSON。可能是您的 API 提供了非 JSON 資料,在這種情況下,此答案或使用 AlamoFire 對其進行解碼都不起作用。但是,將上面的內容格式化為 JSON,在我最好的猜測中,它將給出:
let json = """
{
"id": 1,
"count": "",
"data": [
{
"key1": "value1",
"key2": "value2"
}
],
"message": "SUCCESS",
"response_code": 1
}
"""
此時更明顯的是,data鍵下的內容不是Test上面定義的陣列,而是字典陣列(在示例中的陣列中只有一個 enry)。因此有必要重新指定資料模型。對于這么簡單的事情,對于提到的用例,沒有真正的理由去使用多種型別,所以我們將重新定義 Getdata(盡管不喜歡它,我還是堅持你的命名):
struct Getdata: Decodable {
let all : [[String:String]]
enum CodingKeys: String, CodingKey {
case all = "data"
}
}
為了測驗解碼,讓我們使用標準的 JSONDecoder(我沒有使用 AlamoFire 的 Playground,因為我從不使用它):
do {
let wrapper = try JSONDecoder().decode(Getdata.self, from: Data(json.utf8))
print(wrapper.all)
} catch {
print("Decoding error \(error.localizedDescription)")
}
這輸出
[[“key1”:“value1”,“key2”:“value2”]]
正如預期的那樣。
現在有一個有效的 JSON 解碼解決方案,如果您愿意,應該很容易將其放入 AlamoFire API。盡管如果后端確實提供了格式錯誤的 JSON,那么這將不起作用,您必須更改后端,使用您自己的解碼器對其進行解碼或將其分解為有效的 JSON。
uj5u.com熱心網友回復:
在原始問題中犯了很多愚蠢的錯誤,還有很長的路要走
正如@flanker 所建議的,我確實將資料模型重新指定為
struct Test : Codable {
let id : String?
let message : String?
let data : String?
let count : String?
let response_code : String?
enum CodingKeys: String, CodingKey {
case id = "$id"
case message = "message"
case data = "data"
case count = "count"
case response_code = "response_code"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id)
message = try values.decodeIfPresent(String.self, forKey: .message)
data = try values.decodeIfPresent(String.self, forKey: .data)
count = try values.decodeIfPresent(String.self, forKey: .count)
response_code = try values.decodeIfPresent(String.self, forKey: .response_code)
}
現在它似乎作業了
現在獲得所需的輸出
[["key1": "value1", "key2": "value2"]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446042.html
上一篇:NodeJS-決議物件,其中鍵是使用這些物件屬性作為條件的物件陣列
下一篇:如何逐步決議資料Python?
