【发布时间】:2021-08-10 03:52:04
【问题描述】:
我正在尝试获取“价格”键的值,即“25”
我从后端收到这个响应 Json
{
"errorCode": 0,
"message": "Request successfully served.",
"data": {
"games": {
"TWELVEBYTWENTYFOUR": {
"jackpot_amount": "KES 40,000.00",
"draw_date": "2021-05-21 10:59:45",
"extra": {
"jackpotAmount": 40000,
"unitCostJson": [
{
"currency": "KES",
"price": 25
}
]
},
}
},
"currentTime": {
"date": "2021-05-20 22:28:18.738038"
}
}
}
这是我目前的代码:
fetchData { (dict, error) in
let playerLoginInfo = dataDict["data"] as? NSDictionary
let playerGameInfo = playerLoginInfo?.value(forKey: "games") as? NSDictionary
if let TWELVEBYTWENTYFOUR = playerGameInfo?.value(forKey: "TWELVEBYTWENTYFOUR") as? NSDictionary {
let extra = TWELVEBYTWENTYFOUR.value(forKey: "extra") as? NSDictionary
let unitCostJson = extra?.value(forKey: "unitCostJson") as? NSArray
print("price")
print(unitCostJson?.value(forKey: "price") as? Any)
}
}
我知道这是控制台:
Optional(Optional(<__NSSingleObjectArrayI 0x600001f091d0>(
25
)
))
我已经看到了这个问题How can I access values within Optional NSSingleObjectArrayI?,但我找不到解决方案
编辑:
我现在已经使用 Codeable 来获取数据了:
struct Resp: Codable {
let errorCode: Int
let message: String
let data: Dat
}
struct Dat: Codable {
let games: Games
let currentTime: CurrentTime
}
struct Games: Codable {
let game_code: String
let datetime: String
let estimated_jackpot: String
let guaranteed_jackpot: String
let jackpot_title: String
let jackpot_amount: String
let draw_date: String
let extra: Extra
let next_draw_date: String
let active: String
}
struct Extra: Codable {
let currentDrawNumber: Int
let currentDrawFreezeDate: String
let currentDrawStopTime: String
let jackpotAmount: Int
let unitCostJson: [UnitCostJson]
}
struct UnitCostJson: Codable {
let currency: String
let price: Int
}
struct CurrentTime: Codable {
let date: String
let timezone_type: Int
let timezone: String
}
我现在正在尝试使用此代码从价格中获取价值
do{
let resp:Resp = try JSONDecoder().decode(Resp.self , from:data);
let data = resp.data
let games = data.games
let extra = games.extra
let unitCostJson = extra.unitCostJson
print(unitCostJson[0].price)
}
catch{
GlobalFunctions.shared.callOnMainThread {
self.showAlert(Message: "Something went wrong. Please retry.")
}
}
它正在进入catch
我现在应该如何在 unitCostJson 上获取数据??
【问题讨论】:
-
在 swift 中,不要使用
NS...数据类型,使用它们的 swift 本机等价物。但也不要那样做。创建Codable结构来表示您的数据并使用JSONDecoder。 -
你试图从一个数组中获取一个值,就像它是一个字典一样。首先获取 nsarray 的第一个元素,然后尝试获取关键价格的值
-
如何从数组中获取值
-
使用 Codable 对 json 进行解码,您将不需要这种繁琐的代码逻辑以及强制转换为字典和数组。
-
@Paulw11 我现在按照您的建议使用了
Codable,但无法获得价值。