我想解析以下JSON,以便从Wikipedia的API获取随机文章的ID,并在Swift中使用它:
{
"batchcomplete": "",
"continue": {
"rncontinue": "0.067678657404|0.067678667039|13394072|0",
"continue": "-||"
},
"query": {
"random": [
{
"id": 34538560,
"ns": 3,
"title": "User talk:59.188.42.121"
}
]
}
}
我希望能够从中访问"id"
和"title"
的值,而我目前具有以下访问"query"
的条件:
let url = URL(string: "https://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=1&format=json")
URLSession.shared.dataTask(with: url!) { (data, response, err) in
guard let data = data else { return }
if err != nil {
print(err!)
} else {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
if let result = json! as? [String: AnyObject] {
if let result = result["query"]! as? [String: AnyObject] {
print(result)
}
}
} catch {
print("Error")
}
}
}.resume()
现在,我无法以类型转换来实现自己的目标,而且很快就会变得非常混乱。 我也尝试通过以下类似方法进行类型转换,但无济于事:
[String: [String: [String:AnyObject]]]
是否有更好的方法来访问这些值?任何帮助将不胜感激!
答案 0 :(得分:1)
如果您使用的是Swift 4,则有Codable
。使用Codable
涉及为JSON定义自定义结构/类,但是quicktype.io之类的应用程序可以轻而易举:您只需粘贴JSON并为您生成结构。
首先,用于保存Wikipedia响应的结构:
struct Response: Codable {
struct Query: Codable {
let random: [Random]
}
struct Random: Codable {
let id, ns: Int
let title: String
}
struct Continue: Codable {
let rncontinue, continueContinue: String
enum CodingKeys: String, CodingKey {
case rncontinue
case continueContinue = "continue"
}
}
let batchcomplete: String
let `continue`: Continue
let query: Query
enum CodingKeys: String, CodingKey {
case batchcomplete, `continue`, query
}
}
并解码JSON:
let url = URL(string: "https://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=1&format=json")
URLSession.shared.dataTask(with: url!) { (data, response, err) in
guard let data = data else { return }
guard err == nil else { print(err!); return }
do {
let response = try JSONDecoder().decode(Response.self, from: data)
if let firstArticle = response.query.random.first {
print(firstArticle)
} else {
print("No Article")
}
} catch {
print(error)
}
}.resume()