gpt4 book ai didi

json - 如何在 Swift 中使用数组根解码 JSON

转载 作者:行者123 更新时间:2023-11-30 10:34:10 32 4
gpt4 key购买 nike

我正在尝试解析从 api 请求获得的一些数据。问题是,所有值都没有标签。我想为每个值添加标签,以便稍后在程序中引用标签。

struct dataSet : Codable {
var variable1 : Int
var variable2 : Double
var variable3 : Double
var variable4 : Double
var variable5 : Double
var variable6 : Double
var variable7 : Double
var variable8 : Int
}

struct firsBatch : Codable {
var dataSet : [dataSet]
}

struct results : Codable {
var firsBatch : firsBatch
var last : Int
}

struct allData : Codable {
var errors : [String]
var results : results
}


//some api request code {...}


do {
let decoder = JSONDecoder()
let parsedJSON = try decoder.decode(allData.self, from: data!)
print(parsedJSON)
} catch {
print("JSON error: \(error.localizedDescription)")
}

//数据样本

{"error":[],"results":{"firsBatch":[

[21,"93423.5","324.5","21.0","63.0","1253.0","12.34",1],[42,"314.0","431.1","2341.0","67.1","6567.0","0.8754",4],[12,"4312.1","12.1","43.1","3432.1","0.0","123.432",0],[422,"23442.1","12.1","654.1","12.1","723.1","23.34521",1]

],"last":64274}}

最佳答案

您有一个Variables数组,而不仅仅是一个Variables实例。因此,您的解码类型应该是 [Variables].self,而不是 Variables.self:

let parsedJSON = try detector.decode(variables.self, from: data!)

关于json - 如何在 Swift 中使用数组根解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58442847/

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