【问题标题】:Parse JSON with no title Swift 3解析没有标题的 JSON Swift 3
【发布时间】:2017-04-26 22:07:33
【问题描述】:

我正在拉下一个 json 流?从一个幻像服务器我可以将数据拉下来解析它并在 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()

}

【问题讨论】:

  • lat 只是 s 字符串。
  • 没有标题是什么意思?你有一个字典数组。迭代数组并为每个字典提取所需的任何键值。
  • @rmaddy 我一直在尝试,但我能找到的每个示例都有一个标题,这就是他们能够从字典中提取值的方式。

标签: json swift swift3 nsarray nsdictionary


【解决方案1】:

请阅读 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 中没有任何效果,但教程表明它永远不会消失。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多