没有标题Swift 3解析JSON

时间:2017-04-26 22:07:34

标签: json swift swift3 nsarray nsdictionary

我正在拉下一条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()

}

2 个答案:

答案 0 :(得分:0)

看起来您的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
            }
        }
    }
}

答案 1 :(得分:0)

请阅读JSON。 <form action="" method="post" role="form"> <div class="form-group"> <label for="cellphone">Cellphone Number</label> <input type="text" class="form-control" id="cellphone" minlength="10" placeholder="Cellphone"> </div> <div class="form-group"> <label for="name">Username</label> <input type="text" class="form-control" id="name" placeholder="Username"> </div> <div class="form-group"> <label for="seriesnum">Series Number</label> <input type="text" class="form-control" id="seriesnum" placeholder="Series Number"> </div> <button type="button" class="btn regis-btn" id="register" style="background: #FFCC00;"> <span> Register </span> </button> </form>代表一个数组,[]代表一个字典。

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() 对Swift没有任何影响,但教导中的内容永远不会消失。