试图用奇怪的初始结构解码 json

问题描述

我的 json 代码结构有问题,无法快速解码。 文本中的树看起来像这样:

{
"features": [
    {
        "geometry": {
            "coordinates": [
                21.9877132,38.9953683
            ],"type": "Point"
        },"properties": {
            "country": "Greece","countrycode": "GR","extent": [
                19.2477876,41.7488889,29.7296986,34.7006096
            ],"name": "Greece","osm_id": 192307,"osm_key": "place","osm_type": "R","osm_value": "country","type": "country"
        },"type": "Feature"
    },strong text

this is the link to json

我试图获取坐标和国家/地区代码。 我尝试了很多选择,但都没有奏效,我把我的第一次尝试留在这里,这不起作用,但这是我第一个尝试有意义的:

import Foundation 

struct features: Codable {
  let features: [Features]
}

struct Features: Codable {

  let geometry: [Geometry] 
  let properties: [Properties]
}

struct Geometry: Codable {
  let coordinates: [Double]
}

struct Properties: Codable {
  let country,countrycode,name: String?
}

以及要解码的代码

var coordinates = [features]()
let urlString = "https://photon.komoot.io/api/?q=Greece"
if let url = URL(string: urlString) {
    if let data = try? Data(contentsOf: url) {
        let decoder = JSONDecoder()
        if let jsonCord = try? decoder.decode([features].self,from: data) {
            coordinates = jsonCord
            
        }
    }
}

任何可以向我展示解决此问题的方法的帮助将不胜感激

解决方法

您的数据模型应如下所示:

struct Features: Codable {
    let features: [Feature]
}

struct Feature: Codable {
    let geometry: Geometry
    let properties: Properties
}

struct Geometry: Codable {
    let coordinates: [Double]
}

struct Properties: Codable {
    let country,countrycode,name: String?
}

以及要解码的代码:

var coordinates: [Feature] = []
let urlString = "https://photon.komoot.io/api/?q=Greece"
if let url = URL(string: urlString) {
    if let data = try? Data(contentsOf: url) {
        let decoder = JSONDecoder()
        if let jsonCord = try? decoder.decode(Features.self,from: data) {
            coordinates = jsonCord.features
            
        }
    }
}

,

这是一种称为 GeoJSON 的特殊 JSON 格式。

在 iOS 13 / macOS 15 中,Apple 在 MapKit 中引入了一个 API 来解码此格式:MKGeoJSONDecoder

要获取坐标和国家/地区代码,您只需要一个自定义结构。

import MapKit

struct Country : Decodable {
    let countrycode : String
}

let url = URL(string: "https://photon.komoot.io/api/?q=Greece")!
let task = URLSession.shared.dataTask(with: url) { data,_,error in
    if let error = error { print(error); return }
    
    do {
        let result = try MKGeoJSONDecoder().decode(data!) as! [MKGeoJSONFeature]
        if let feature = result.first,let propertyData = feature.properties {
            let country = try JSONDecoder().decode(Country.self,from: propertyData)
            print(country.countrycode)
            if let annotations = feature.geometry as? [MKPointAnnotation],let coordinate = annotations.first?.coordinate {
                print(coordinate)
            }
        }
    } catch {
        print(error)
    }
}
task.resume()