Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图用奇怪的初始结构解码json_Json_Swift_Jsondecoder - Fatal编程技术网

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

试图用奇怪的初始结构解码json,json,swift,jsondecoder,Json,Swift,Jsondecoder,我有一个json代码结构的问题,我不能解码到swift。 文本中的树如下所示: { "features": [ { "geometry": { "coordinates": [ 21.9877132, 38.9953683 ], "type": "P

我有一个json代码结构的问题,我不能解码到swift。 文本中的树如下所示:

{
"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

我想知道坐标和国家代码。 我尝试了很多选择,但都没有成功,我把我的第一次尝试留在这里,虽然没有成功,但这是我第一次尝试的原因:

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
            
        }
    }
}
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
            
        }
    }
}


如果您能为我提供解决此问题的方法,我将不胜感激。

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

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 = [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
            
        }
    }
}
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
            
        }
    }
}


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

在iOS 13/macOS 15中,苹果在
MapKit
中引入了一个API来解码这种格式:

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

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()

解决这个问题的第一步是使用正确的错误处理,使用
try
do/catch
而不是
try?
并在catch子句中打印错误。谢谢,根对象(以及
geometry
properties
)显然是一个字典,而不是一个数组。(注意
{}
)并请始终以大写字母开头命名结构。永远不要用同步的
数据从远程URL加载数据(内容:
structs始终以大写开头,请检查。远程URL将不会被使用,只是这里有一个问题。是的,它们是一个字典,我不知道如何处理。感谢vadian花时间将字典变成一个结构(没有括号).正如Joakim编写的打印
错误
,它会准确地告诉您出了什么问题。感谢vadian提供的额外信息,了解这些信息非常有用。