如何在没有密钥的情况下解析 JSON 文件?
Posted
技术标签:
【中文标题】如何在没有密钥的情况下解析 JSON 文件?【英文标题】:How I can parse JSON file without keys? 【发布时间】:2017-04-21 14:23:24 【问题描述】:我已经从这个网址下载了 JSON 文件:https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json
我将所有 JSON 文件解析为 let json
后卡住了
let requestURL: NSURL = NSURL(string: "https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest)
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200)
do
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print (json)
catch
print("Error with Json: \(error)")
task.resume()
问题是我不能转向每个国家和每个城市,因为我不知道 key->value。我怎样才能转向每个国家和城市?
【问题讨论】:
Iterating Through a Dictionary in Swift的可能重复 查看 Swift 文档 developer.apple.com/library/content/documentation/Swift/… 遍历字典 【参考方案1】:这里有一些 Swift Playground 代码可以完全满足您的需求:
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let urlStr = "https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json"
let requestURL: URL = URL(string: urlStr)!
let urlRequest: URLRequest = URLRequest(url: requestURL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest)
(data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200)
do
let json:[String:[String]] = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary
for (country, cities) in json
print(country)
for city in cities
print("City in \(country): \(city)")
catch
print("Error with Json: \(error)")
else
print("Other status: \(statusCode)")
task.resume()
他们的关键是知道数据的格式,在本例中是包含 String
键和 String
值数组的字典。当你声明你的 json 变量时,将它转换为它的实际值:
let json:[String:[String]] = try! JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! Dictionary
【讨论】:
它的作品。非常感谢你。现在对我来说很清楚【参考方案2】:在此回复中,您可以找到有关国家和城市的所有数据。
您的响应是字典 [String:[String]]
类型。
例子:
部分回复:
let json = ["Eritrea":["Asmara",""],"Cuba":["Havana","Habana","La Habana","Matanzas","Villa","Bayamo","Cienfuegos","Santiago de Cuba","HolguÃn","Ciego de Ãvila","Pinar del RÃo","Sancti SpÃritus","Camagüey","Las Tunas","Guantánamo","Varadero"],"Saint Helena":["Tristan Da Cunha","Jamestown"],"Christmas Island":["Flying Fish Cove"],"Ethiopia":["Addis Ababa","Awasa","Jijiga"],"British Indian Ocean Territory":[""]]
因此,如果您想获取所有国家/地区名称,只需这样做:
let keys = Array(json.keys)
如果您想获取例如 厄立特里亚 的城市,请执行以下操作:
let cityes = json["Eritrea"]
【讨论】:
以上是关于如何在没有密钥的情况下解析 JSON 文件?的主要内容,如果未能解决你的问题,请参考以下文章
如何在没有外部递归函数的情况下解析多个嵌套的 JSON 键?