【问题标题】:Swift GeoJson ParseSwift GeoJson 解析
【发布时间】:2020-08-29 08:10:03
【问题描述】:
{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [
      126.9823439963945,
      37.56461982743129
    ]
  }
},
{
  "type": "Feature",
  "geometry": {
    "type": "LineString",
    "coordinates": [
      [
        126.9823439963945,
        37.56461982743129
      ],
      [
        126.98230789017299,
        37.564453179812105
      ],
      [
        126.98210513804034,
        37.563703265276516
      ],
      [
        126.98207180945346,
        37.56352550784786
      ],
      [
        126.9817857308457,
        37.56284502921221
      ],
      [
        126.98166907678578,
        37.562633941789535
      ],
      [
        126.98157186492477,
        37.56247284870586
      ],
      [
        126.98128300624569,
        37.56205345097403
      ],
      [
        126.98124689891416,
        37.56200067907546
      ]
    ],
    "traffic": [0, 8, 4, 12]
  }}

这就是我得到的。 而且我不知道解析关键的“坐标”。 此类型取决于几何类型。 如果 type 为“Point”,则 type 变为 [String]。 如果类型为“LineString”,则类型变为 [[String]]。 我该如何解决?

【问题讨论】:

  • 我的回答能回答你的问题吗?如果是,请考虑通过单击该复选标记接受它!

标签: json parsing codable


【解决方案1】:

您可以使用这个可可豆荚:CodableGeoJSON

它为您编写了Codable 结构。您似乎在这里有一个几何形状未知的特征,因此您可以执行以下操作:

let geoJSON = try JSONDecoder().decode(GeoJSON.self, from: geoJSONData)
guard case .feature(let feature) = geoJSON else {
    // the GeoJSON does not contain a feature!
}

// handle each kind of geometry...
switch feature.geometry {
case .point(let coordinates): // coordinates is a GeoJSONPosition
    // ...
case .multiPoint(let coordinates): // coordinates is a [GeoJSONPosition]
    // ...
case .lineString(let coordinates): // coordinates is a [GeoJSONPosition]
    // ...
case .multiLineString(let coordinates): // coordinates is a [[GeoJSONPosition]]
    // ...
case .polygon(let coordinates): // coordinates is a [[GeoJSONPosition]]
    // ...
case .multiPolygon(let coordinates): // coordinates is a [[[GeoJSONPosition]]]
    // ...
case .geometryCollection(let geometries):
    // ...
}

如果您不喜欢为此使用库,请查看他们的源代码并尝试从中学习,具体来说,GeoJSON.swift

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-25
    • 2017-08-02
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2019-01-08
    相关资源
    最近更新 更多