在Swift中解析嵌套数组JSON

时间:2018-12-07 18:18:13

标签: ios json swift

我正在尝试解析JSON,希望大家能帮帮我。如何在Swift 4中解码?我需要获取没有类型的第二组坐标内的值。 这是JSON代码:

{
  "geo": [{
    "area": 153.2295,
    "tipo": "ARL_TOTAL",
    "geoJson": {
      "type": "MultiPolygon",
      "coordinates": [
        [
          [
            [-54.869875405035, -7.7332162703037],
            [-54.87000906538, -7.7333509322313],
            [-54.870081208559, -7.7334236160148]
          ]
        ],
        [
          [
            [-54.866741527372, -7.7218185563672],
            [-54.869847964562, -7.733188624206],
            [-54.866741527372, -7.7218185563672]
          ]
        ]
      ]
    }
  }]
}

1 个答案:

答案 0 :(得分:0)

我要访问坐标,可以执行以下操作:

struct NestedJSON: Codable {
    let type: String
    let coordinates: [[[[Double]]]]
}

struct Area: Codable {
    let area: Double
    let tipo: String
    let geoJson: NestedJSON
}

struct JSONExample: Codable {
    let geo: [Area]
}

if let url = Bundle.main.url(forResource: "example", withExtension: "json") {
    do {
        let data = try Data(contentsOf: url)
        let json = try? JSONDecoder().decode(JSONExample.self, from: data)

        json?.geo.first?.geoJson.coordinates
            .compactMap {$0}
            .forEach { print($0.flatMap {$0}) }

    } catch {
        print("error:\(error)")
    }
}

您需要与coordinates对象一起玩一些,可以使用Playgrounds。