gpt4 book ai didi

ios - Swift 5 Alamofire 字典解析错误

转载 作者:行者123 更新时间:2023-11-28 23:21:45 25 4
gpt4 key购买 nike

我想在 Swift 5 中使用 Alamofire 解析 json,但我没有在下面的代码中获取数组。

我的json文件

[{"type":"success","data":[{"id":"1","sectionId":"1","title":"test title","detail":"detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text detail test text ","image":"test.jpg","view":"0","status":"1"}]}]

我的 swift 5 代码

if let json = response.result.value {
print(json)
if let dictionaryArray = json as? Dictionary<String, AnyObject?> {
print(dictionaryArray)
let json = dictionaryArray
if let type = json["type"] as? String,
let results = json["data"] as? Array<Dictionary<String, AnyObject?>> {
print(type)
for i in 0..<results.count{
let json = results[i]
if let id = json["id"] as? String, let jokeString = json["title"] as? String{
self.items.append(Item(id: id, sectionId : "0", title: jokeString, detail:"", image: "", view : "0", status : "0"))
print(json)

}
}
}
}
}
}

有什么想法吗?我哪里做错了?

最佳答案

根是一个数组,所以它的 [[String:Any]]

 if let dictionaryArray = json as? [[String:Any]] {

顺便说一句,最好使用 Codable

Alamofire.request(url, method: .get, parameters: [:], encoding: JSONEncoding.default, headers: [:]).responseData { res in
guard let data = res.data else { return }

do {
let res = try JSONDecoder().decode([Root].self, from:data)
print(res)
}
catch {
print(error)
}
}

struct Root: Codable {
let type: String
let data: [Datum]
}

// MARK: - Datum
struct Datum: Codable {
let id, sectionID, title, detail: String
let image, view, status: String

enum CodingKeys: String, CodingKey {
case id
case sectionID = "sectionId"
case title, detail, image, view, status
}
}

编辑:

if let dictionaryArray = json as? [[String:Any?]] {
for item in dictionaryArray {
if let type = item["type"] as? String,let results = item["data"] as? [[String:Any?]] {
print(type)
for json in results {
if let id = json["id"] as? String, let jokeString = json["title"] as? String {
self.items.append(Item(id: id, sectionId : "0", title: jokeString, detail:"", image: "", view : "0", status : "0"))
print(json)
}
}
}
}
}

关于ios - Swift 5 Alamofire 字典解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59553826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com