我已经花了好几个小时从应用包中的JSON文件中读取值并打印这些值。我一直在搜索几个论坛和SO问题试图拼凑一个从.json文件中读取的方法,但没有运气。我目前拥有的是一堆(可能无用的)代码,如下所示:
//json parsing
if let path = Bundle.main.path(forResource: "POIs", 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 pois = jsonResult["POI"] {
print("test ", pois)
for poi in pois as! [AnyObject] {
guard let name = poi["name"], //String
let coordinatesJSON = poi["coordinates"] as? [String: Double],
let latitudeVar = coordinatesJSON["lat"],
let longitudeVar = coordinatesJSON["lng"],
let altitude = poi["altitude"], //Int
let facebookurl = poi["facebookurl"], //String
let poiImage = poi["pinImage"] //String
else {
return
}
我的POIs.json文件如下所示:
{
"POI":[
{
"name": "Boston Paintball",
"coordinates": {
"lat": 42.401848,
"lng": -71.023843
},
"altitude": 7,
"facebookurl": "https://www.facebook.com/PlayBostonPaintball/",
"pinImage": "bp"
},
{
"name": "Chilis",
"coordinates": {
"lat": 42.402314,
"lng": -71.021655
},
"altitude": 7,
"facebookurl": "https://www.facebook.com/chilis",
"pinImage": "chilis"
}
]
}
有人能告诉我从json读取值的最佳方法,将它们存储到我指定的变量中,然后打印出来吗?谢谢!
更新代码:
//json parsing
let file = Bundle.main.url(forResource: "POIs", withExtension: "json")
let data = try? Data(contentsOf: file!)
let root = try? JSONDecoder().decode(Root.self, from: data!)
do {
let root = try JSONDecoder().decode(Root.self, from: data!)
print(root)
} catch {
print(error)
}
let decoder = JSONDecoder()
let pois = try? decoder.decode([Root].self, from: data!)
let pinUIImage = UIImage(named: Location.pinImage)
但仍然给我Instance member 'pinImage' cannot be used on type 'ViewController.Location'
错误。
更新2:
for poi in (root?.pointsOfInterest)! {
if let location = root?.pointsOfInterest.??? { //I dont know how to grab the poi from the current iteration. Any tips?
答案 0 :(得分:1)
您应该构建数据以符合Codable协议:
struct Root: Codable {
let pointsOfInterest: [Location]
private enum CodingKeys: String, CodingKey {
case pointsOfInterest = "POI"
}
}
struct Location: Codable {
let name: String
let coordinates: Coordinate
let altitude: Int
let facebookurl: String
let pinImage: String
}
struct Coordinate: Codable {
let latitude: Double
let longitude: Double
private enum CodingKeys: String, CodingKey {
case latitude = "lat", longitude = "lng"
}
}
do {
let root = try JSONDecoder().decode(Root.self, from: jsonData)
print(root)
} catch {
print(error)
}
这将打印
Root(pointsOfInterest:[__ lldb_expr_39.Location(名称:“波士顿) Paintball“,坐标:__ lldb_expr_39.Coordinate(纬度: 42.401848000000001,经度:-71.023842999999999),海拔高度:7,facebookurl:“https://www.facebook.com/PlayBostonPaintball/”, pinImage:“bp”),__ lldb_expr_39。位置(名称:“Chilis”,坐标: __lldb_expr_39.Coordinate(北纬:42.402313999999997,经度:-71.021654999999996),海拔高度:7,facebookurl:“https://www.facebook.com/chilis”,pinImage:“chilis”)])