-1

I was trying to convert NSData to Json by doing this:

    let jdata = getJSON("https://api.myjson.com/bins/16j2i")

    do {
        let json = try NSJSONSerialization.JSONObjectWithData(jdata, options: []) as! [String: AnyObject]
        print(json)
    } catch {
        print("\(error)")
    }

This is the getJSON method

func getJSON(url:String) -> NSData {
    return NSData(contentsOfURL: NSURL(string: url)!)!
}

A error says that could not cast value of type '_NSCFArray' to 'NSDictionary'. Any ideas? Please

Joey Zhang
  • 363
  • 6
  • 18

3 Answers3

1

The root element of your JSON is array not dictionary (Your format looks something like [{...},{...}] ). For fixing this error you need to change the parsing code to:

let json = try NSJSONSerialization.JSONObjectWithData(jdata, options: []) as! [[String: AnyObject]]
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
0
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
let convert_array = responseString?.description
// Convert server json response to NSDictionary
do {
    if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray {
       print(convertedJsonIntoDict)
    }
GYaN
  • 2,327
  • 4
  • 19
  • 39
Softlabsindia
  • 791
  • 6
  • 11
-1
let data = text.data(using: String.Encoding.utf8)

let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]

Working Fine for Swift 3.1 & Swift 4

Softlabsindia
  • 791
  • 6
  • 11