如何在Swift中使用值作为键和字典作为数组解析JSON

时间:2020-03-22 13:39:07

标签: json swift

我试图从Swift中的网站api解析JSON数据,但是api有点奇怪。以下是有效的方法:[https://www.avanderlee.com/swift/json-parsing-decoding/][1]

这是要解析/翻译的结构:

{
  "Meta Data": {
    "1. Information": "some info",
    "2. Symbol": "string symbol",
    "3. Last Refreshed": "2020-03-20 16:00:00",
    "4. Interval": "5min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (5min)": {
    "2020-03-20 16:00:00": {
      "1. keyABC": "138.2700",
      "2. keyCBA": "138.4900",
      "3. keyCAB": "136.6500",
      "4. keyACB": "136.7800",
      "5. keyBAC": "3392530"
    },
    "2020-03-20 15:55:00": {
      "1. keyABC": "137.7825",
      "2. keyCBA": "139.9112",
      "3. keyCAB": "137.0365",
      "4. keyACB": "138.2925",
      "5. keyBAC": "2463243"
    },
    "2020-03-20 15:50:00": {
      "1. keyABC": "139.0000",
      "2. keyCBA": "139.0150",
      "3. keyCAB": "137.7500",
      "4. keyACB": "137.7500",
      "5. keyBAC": "1051283"
    },
    ...
  }
}

问题1:有些随机键是我需要的值,不知道如何在不删除的情况下进行解析 问题2:JSON库不在数组中,而在新对象中。但是目标是用它制作一个Swift数组

我想知道是否有一种简单的方法可以使用JSONDecode解析上述内容(如果有的话,最好的方法是什么?)。

1 个答案:

答案 0 :(得分:1)

app.quicktype.io为解析此JSON提供了一个很好的起点:

struct JSONData: Codable {
    let metaData: MetaData
    let timeSeries5Min: [String: TimeSeries5Min]

    enum CodingKeys: String, CodingKey {
        case metaData = "Meta Data"
        case timeSeries5Min = "Time Series (5min)"
    }
}

struct MetaData: Codable {
    let the1Information, the2Symbol, the3LastRefreshed, the4Interval: String
    let the5OutputSize, the6TimeZone: String

    enum CodingKeys: String, CodingKey {
        case the1Information = "1. Information"
        case the2Symbol = "2. Symbol"
        case the3LastRefreshed = "3. Last Refreshed"
        case the4Interval = "4. Interval"
        case the5OutputSize = "5. Output Size"
        case the6TimeZone = "6. Time Zone"
    }
}

struct TimeSeries5Min: Codable {
    let the1KeyABC, the2KeyCBA, the3KeyCAB, the4KeyACB: String
    let the5KeyBAC: String

    enum CodingKeys: String, CodingKey {
        case the1KeyABC = "1. keyABC"
        case the2KeyCBA = "2. keyCBA"
        case the3KeyCAB = "3. keyCAB"
        case the4KeyACB = "4. keyACB"
        case the5KeyBAC = "5. keyBAC"
    }
}

鉴于将所需的任何数据提取到数组中应该相当容易。