我一直在研究这个项目的核心数据。 我需要从 json 文件检索数据,然后将某些数据获取到核心数据中。但是,我陷入了类型转换。
[![do {
let][1]][1] jsonDict = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments) as! NSDictionary
let jsonArray = jsonDict.value(forKeyPath: "response.venues") as! NSArray
for jsonDictionary: NSDictionary in jsonArray {
let venueName = jsonDictionary["name"] as? String
let venuePhone = (jsonDictionary as AnyObject).value(forKeyPath: "contact.phone") as? String
let specialCount = (jsonDictionary as AnyObject).value(forKeyPath: "specials.count") as? NSNumber
let locationDict = jsonDictionary["location"] as! NSDictionary
let priceDict = jsonDictionary["price"] as! NSDictionary
let statsDict = jsonDictionary["stats"] as! NSDictionary
let location = Location(entity: locationEntity!, insertInto: coreDataStack.context)
location.address = locationDict["address"] as? String
location.city = locationDict["city"] as? String
location.state = locationDict["state"] as? String
location.zipcode = locationDict["postalCode"] as? String
location.distance = locationDict["distance"] as? NSNumber
let category = Category(entity: categoryEntity!, insertInto: coreDataStack.context)
let priceInfo = PriceInfo(entity: priceEntity!, insertInto: coreDataStack.context)
priceInfo.priceCategory = priceDict["currency"] as? String
let stats = Stats(entity: statsEntity!, insertInto: coreDataStack.context)
stats.checkinsCount = statsDict["checkinsCount"] as? NSNumber
stats.usersCount = statsDict["userCount"] as? NSNumber
stats.tipCount = statsDict["tipCount"] as? NSNumber
let venue = Venue(entity: venueEntity!, insertInto: coreDataStack.context)
venue.name = venueName
venue.phone = venuePhone
venue.specialCount = specialCount
venue.location = location
venue.category = category
venue.priceInfo = priceInfo
venue.stats = stats
}
我尝试了几个下标,根本不起作用。如何解决这个问题?提前致谢。
最佳答案
1) 尝试使用 [Any]
而不是 NSArray
和 [String:Any]
而不是 NSDictionary
2) 您可能需要从 response
venues
在 Swift 3 中像这样:
do {
let jsonDict = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments) as! [String:Any]
let jsonResponseArray = jsonDict["response"] as! [Any]
let jsonVenueArray = jsonResponseArray["venues"] as! [String:Any]
for venue: [String:Any] in jsonVenueArray {
...
}
} catch {
print("Error:", error)
}
关于ios - JSON "Any"不可转换为 'NSDictionary' 以及如何确定转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927745/