使用JSON文件在MapKit中添加Swift注释

使用JSON文件在MapKit中添加Swift注释,json,swift,mapkit,mapkitannotation,Json,Swift,Mapkit,Mapkitannotation,我试图从JSON文件在MapKitView上添加注释。 这是我的密码: // On récupère les valeurs JSON func loadInitialData() { if let path = Bundle.main.path(forResource: "Playgrounds", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath

我试图从JSON文件在MapKitView上添加注释。 这是我的密码:

// On récupère les valeurs JSON
func loadInitialData() {
    if let path = Bundle.main.path(forResource: "Playgrounds", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
            print(jsonResult)
            let jsonResultAs = jsonResult as? Dictionary<String, AnyObject>
            print(jsonResultAs!)
            let playground = jsonResultAs!["playgrounds"] as? [Any]
            print(playground!)
            // 5
            let validWorks = playground.flatMap { Playground(json: $0) }
            playgrounds.append(validWorks!)
        } catch {
            // handle error
        }
    }
如果让latitude=Doublejson[4]as!串

我不明白为什么它不起作用,我在跟踪,但我知道我错过了一些东西。。。我希望有人能帮助我

我的JSON结构文件:

[{
    ComLib = Ambronay;
    DepCode = 1;
    DepLib = Ain;
    EquEclairage = "-1";
    EquGpsX = "5.3625";
    EquGpsY = "46.0075";
    InsNom = "Terrain de basket";
    NatureLibelle = Decouvert;
    NatureSolLib = Sable;
}, {
    ComLib = Ambutrix;
    DepCode = 1;
    DepLib = Ain;
    EquEclairage = "-1";
    EquGpsX = "5.34";
    EquGpsY = "45.93889";
    InsNom = "Ecole Primaire";
    NatureLibelle = Decouvert;
    NatureSolLib = Bitume;
},
etc...
}]
谢谢。

这一行

Double(json[4] as! String)
崩溃,因为json是一个字典数组,您希望强制将字典转换为字符串,这是您可能需要的旧方法

var allCoor = [CLLocationCoordinate2D]()

init?(json: [Any]) { 

    if let content = json as? [[String:Any]] { 
       content.forEach {
          if let latitude = $0["EquGpsX"] as? String , let longitude = $0["EquGpsY"] as? String
             self.allCoor.append( CLLocationCoordinate2D(latitude:Double(latitude)!, longitude: Double(longitude)!))
          }
          else {
            ///// 
          } 
       }
    } 
}

但是正确的方法是使用Codable

PostJSON,因为它在捆绑包中,所以我们可以帮助您解码
var allCoor = [CLLocationCoordinate2D]()

init?(json: [Any]) { 

    if let content = json as? [[String:Any]] { 
       content.forEach {
          if let latitude = $0["EquGpsX"] as? String , let longitude = $0["EquGpsY"] as? String
             self.allCoor.append( CLLocationCoordinate2D(latitude:Double(latitude)!, longitude: Double(longitude)!))
          }
          else {
            ///// 
          } 
       }
    } 
}