嘿,我有以下JSON:
{
"monuments": [
{
"name": "Iglesia de Tulyehualco",
"description": "No hay descripción",
"latitude": 19.2544877,
"longitude": -99.012157
},
{
"name": "Casa de Chuyin",
"description": "Casa de Jesús",
"latitude": 119.2563629,
"longitude": -99.0152632
}
]
}
我得到以下代码来尝试解析每个对象,但我收到类型为Any没有成员'x'的错误。
func loadMonuments() {
if let path = Bundle.main.path(forResource: "monuments", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let monumentsJson = jsonResult["monuments"] as? [Any] {
for m in monumentsJson {
print(m)
}
}
} catch {
// handle error
}
}
}
我想获得纪念碑的每个属性。
答案 0 :(得分:2)
选项1:(推荐)
struct Root:Decodable {
let monuments:[InnerItem]
}
struct InnerItem:Decodable {
let name:String
let description:String
let latitude:Doube
let longitude:Double
}
//
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options:[])
let content = try JSONDecoder().decode(Root.self,from:data)
print(content)
}
catch {
print(error)
}
选项2:
if let jsonResult = jsonResult as? [String:Any] , let monumentsJson = jsonResult["monuments"] as? [[String:Any]] {
for m in monumentsJson {
print(m["name"])
}
}
答案 1 :(得分:0)
在Swift4中引入了Codable
用于序列化,因此您必须尝试使对象成为可编码对象,如下所示:
struct Monument: Codable {
let name: String
let description: String
let latitude: String
let longitude: String
}
然后您可以使用以下方法解析对象:
func loadMonuments() -> [Monument] {
guard let path = Bundle.main.path(forResource: "monuments", ofType: "json"),
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) else {
return []
}
do {
return try JSONDecoder().decode([Monument].self, from: data)
} catch {
print("error: \(error)")
return []
}
}