解析 JSON 没有标题 Swift 3

Parse JSON with no title Swift 3

我正在下拉 json 流?从 phant 服务器,我可以将数据拉下来解析它并在 xcode 中打印它。我需要提取特定值,但 json 没有标题,我似乎无法弄清楚。

我的JSON数据

(
    {
    lat = "36.123450";
    long = "-97.123459";
    timestamp = "2017-04-26T05:55:15.106Z";
},

我的当前代码在 Swift

    let url = URL(string: "https://data.sparkfun.com/output/5JDdvbVgx6urREAVgKOM.json")

let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
        print("error")
    } else {
        if let content = data {
            do {
                // JSONArray 
                let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                print(myJson)
                let Coordinates = myJson["lat"] as! [[String:Any]]
                print(Coordinates)


            } catch {
        }
    }
    }
}
    task.resume()

}

看起来您的 JSON 数据是一个对象数组,因此 myJson 将是一个字典数组。

我会尝试这样的事情:

if let myJson = try JSONSerialization.jsonObject(with: content, options: []) as? [AnyObject] {
    print(myJson)
    for obj in myJson {
        if let dict = obj as? [String:AnyObject] {
            print(dict)
            if let lat = dict["lat"] as? String,
                let lng = dict["long"] as? String,
                let time = dict["timestamp"] as? String {
                    // do something with stuff
            }
        }
    }
}

请阅读JSON。 []代表一个数组,{}一个字典。

JSON是字典数组。所有键和值都是 String.

let url = URL(string: "https://data.sparkfun.com/output/5JDdvbVgx6urREAVgKOM.json")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
        print("error: ", error!)
    } else {
        do {
            let coordinateArray = try JSONSerialization.jsonObject(with: data!) as! [[String:String]]
            for coodinate in coordinateArray {
                let lat = coodinate["lat"] ?? "n/a"
                let long = coodinate["long"] ?? "n/a"
                let timestamp = coodinate["timestamp"] ?? "n/a"
                print("latitude: \(lat), longitude: \(long), timestamp: \(timestamp)")
            }

        } catch {
            print (error)
        }
    }
}
task.resume()

一如既往,.mutableContainers 在 Swift 中没有任何效果,但暗示它永远不会消失的教程。