如果您在 Swift 中表示此结构,请对字典和数组使用方括号。并且不要忘记打开可选项:
let z = [
[
"Name":[
"First":"Tika",
"Last":"Pahadi"
],
"City":"Berlin",
"Country":"Germany"
]
]
if let name = z[0]["Name"] as? [String: String], let firstName = name["First"] {
// use firstName here
}
但是,假设您确实收到了该 JSON 是由于某个网络请求与URLSession 的结果。然后你可以用JSONSerialization解析它:
do {
if let object = try JSONSerialization.jsonObject(with: data) as? [[String: Any]],
let name = object[0]["Name"] as? [String: String],
let firstName = name["First"] {
print(firstName)
}
} catch {
print(error)
}
或者更好,在 Swift 4 中,我们会使用 JSONDecoder:
struct Name: Codable {
let first: String
let last: String
enum CodingKeys: String, CodingKey { // mapping between JSON key names and our properties is needed if they're not the same (in this case, the capitalization is different)
case first = "First"
case last = "Last"
}
}
struct Person: Codable {
let name: Name
let city: String
let country: String
enum CodingKeys: String, CodingKey { // ditto
case name = "Name"
case city = "City"
case country = "Country"
}
}
do {
let people = try JSONDecoder().decode([Person].self, from: data) // parse array of `Person` objects
print(people)
} catch {
print(error)
}