[英]Swift nested Json
我有一個輸出公交車Json列表的URL。
{"buses":
[
{"time_id”:"56555","bustime":"10:00 AM","price":"30.00","group_id":"1234"},
{"time_id":"56525",”bustime":"11:00 AM","price":"40.00","group_id":"1235"}
]}
以下對我而言總是如此,以便如此檢索每條總線:
let url = NSURL(string: "https://www.json_output_url.com:")
if let JSONData = NSData(contentsOfURL: url!)
{
if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary
{
if let BusArray = json["buses"] as? [NSDictionary]
{
for item in BusArray
{
現在,輸出已更改,並且Buss數組嵌套在外部數組中,如下所示:
{"results":[
{"buses":
[
{"time_id”:"56555","bustime":"10:00 AM","price":"30.00","group_id":"1234"},
{"time_id":"56525",”bustime":"11:00 AM","price":"40.00","group_id":"1235"}
]}
]}
而且我不再可以檢索Buss數組,因為它是嵌套的。 我不想使用諸如Swiftyjson之類的庫,而只是想調整我的簡單代碼以能夠檢索較低層次結構中的內容。 如何實現的?
EDITED2答案:
if let BusArray = json["buses"] as? [[String: AnyObject]] // downcast to array of NSDictionary
{
for item in BusArray
{
let timeId = item["time_id"] as? String
let bustime = item["bustime"] as? String
:
注意:我想您正在使用NSData(contentsOfURL :)進行測試。 注意在實際應用中改用異步方法。
這是解碼新JSON數據的安全方法:
if let url = NSURL(string: "https://www.json_output_url.com:"),
JSONData = NSData(contentsOfURL: url),
json = try? NSJSONSerialization.JSONObjectWithData(JSONData, options: []),
dict = json as? [String: AnyObject],
results = dict["results"] as? [[String: AnyObject]] {
for result in results {
if let buses = result["buses"] as? [[String: String]] {
for bus in buses {
print(bus)
if let time = bus["bustime"] {
print("Time: \(time)")
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.