首页 > 解决方案 > Swift 中 JSON 的变量结构

问题描述

您好,我以这种方式在我的脚本中使用 JSON:

//Top of Script

struct Runway: Decodable {
let ident1: String }

struct Runways: Decodable {
let runways: [Runway]

init(runways: [Runway]) {
    self.runways = runways
}
}

//Getting Values
let aero4 = try decoder.decode(Runways.self, from: data)
print(aero4.runways.ident1)

{ "runways": [
    {
      "ident1": "13R",

所以上面打印出 13R。现在我如何构造我的代码以便我可以检索任何 json,假设如果用户键入 LA,则 json 将返回第一个 [] 作为 [runwaysLA],所以基本上 JSON 返回中的第一个 [] 总是不同的并且对用户来说是可变的输入?不太确定如何将结构与变量一起使用

{ "runwaysLA": [
    {
      "ident1": "13R",

或者

 { "runwaysBA": [
            {
              "ident1": "13C",

或者

 { "runwaysWA": [
            {
              "ident1": "13L",

标签: jsonswiftparsingvariablesstruct

解决方案


一个简单的解决方案是消除显式Runways结构并直接解析为字典,如下所示:

struct Runway: Decodable {
    let ident1: String
}

typealias Runways = [String: [Runway]]

do {
    let r = try JSONDecoder().decode(Runways.self, from: str.data(using: .utf8)!)

    // example: get the first ident from WA, if present
    if let rwa = r["runwaysWA"], !rwa.isEmpty {
        print(rwa[0].ident1)
    }
} catch {
    print(error)
}


推荐阅读