【问题标题】:How to get value from Optional(Optional(<__NSSingleObjectArrayI >(25)))如何从 Optional(Optional(<__NSSingleObjectArrayI >(25))) 中获取值
【发布时间】: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,但无法获得价值。

标签: ios json swift


【解决方案1】:

我删除了你的结构并删除了所有不相关的属性(与 json 相比),如果你想将它们添加回来,那么你需要使用 CodingKey 枚举

struct Resp: Codable {
    let errorCode: Int
    let message: String
    let data: Dat
}
struct Dat: Codable {
    let games: [String:Games]
    let currentTime: CurrentTime
}

struct Games: Codable {
    let extra: Extra
}
struct Extra: Codable {

    let unitCostJson: [UnitCostJson]
}
struct UnitCostJson: Codable {
    let currency: String
    let price: Int
}

struct CurrentTime: Codable {
    let date: String
}

现在你可以像这样访问unitCost

let unitCost = resp.data.games["TWELVEBYTWENTYFOUR"]?.extra.unitCostJson

【讨论】:

  • 你是如何初始化result变量的?
  • 我在 catch keyNotFound(CodingKeys(stringValue: "games", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"games\", intValue: nil) (\"games\").", underlyingError: nil)) 中收到此错误
  • 我从结果改为了resp,它们是一样的。第二题没看懂
  • 我现在回到我的电脑前,仔细检查了我发布的代码,它按预期工作。
猜你喜欢
  • 2020-06-14
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
相关资源
最近更新 更多