Nan
Nan

Reputation: 524

JSON "Any" is not covertible to 'NSDictionary' and how to decide the casting type

I have been working on core data in this project. I need to retrieve data from a json file then get certain data into core data. However, i get stuck on type casting.

[![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
  }

enter image description here

And my JSON tree is here as well:enter image description here

I have been try a few subscript, which does not work at all. How to solve this issue? Thanks in advance.

Upvotes: 0

Views: 57

Answers (1)

Sebastian
Sebastian

Reputation: 6384

1) Try to use [Any] instead of NSArray and [String:Any] instead of NSDictionary

2) You will probably need to extract venues from response

Like this in 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)
}

Upvotes: 1

Related Questions