簡體   English   中英

在Swift中解析嵌套數組JSON

[英]Parsing nested array JSON in 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]
          ]
        ]
      ]
    }
  }]
}

我要訪問坐標,可以執行以下操作:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM