Search code examples
jsonswifterror-handlingnsmutablearrayjsonserializer

Swift JSONSerialization.jsonObject Error


I've looked around but I don't find an answer to fix this error that has been bugging me. I tried adding a "as! NSMutableArray" but that gave me another error. Any ideas on how to fix it? I converted my project from Objective-C to Swift, so hopefully the code is all good I had 20+ errors now I'm down to 3 errors. Thank you.

Error Message:

'jsonObject' produces 'Any', not the expected contextual result type 'NSMutableArray'

code error picture

Code for retrieving data from server

// Retrieving Data from Server
func retrieveData() {

    let getDataURL = "http://ip/example.org/json.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {

        let data: NSData = try NSData(contentsOf: url as URL)
        jsonArray = JSONSerialization.jsonObject(with: data, options: nil)
    }
    catch {
        print("Error: (data: contentsOf: url)")
    }

    // Setting up dataArray
    var dataArray: NSMutableArray = []

    // Looping through jsonArray
    for i in 0..<jsonArray.count {

        // Create Data Object

        let dID: String = (jsonArray[i] as AnyObject).object(forKey: "id") as! String
        let dName: String = (jsonArray[i] as AnyObject).object(forKey: "dataName") as! String
        let dStatus1: String = (jsonArray[i] as AnyObject).object(forKey: "dataStatus1") as! String
        let dStatus2: String = (jsonArray[i] as AnyObject).object(forKey: "dataStatus2") as! String
        let dURL: String = (jsonArray[i] as AnyObject).object(forKey: "dataURL") as! String

        // Add Data Objects to Data Array
        dataArray.add(Data(dataName: dName, andDataStatus1: dStatus1, andDataStatus2: dStatus2, andDataURL: dURL, andDataID: dID))
    }

    self.myTableView.reloadData()
}

Solution

  • The jsonObject function will return a value of type Any but the jsonArray's type of NSMutableArray. And this function will throw an error if something is wrong, put a try keyword before it. In my experience, let change the type of jsonArray to array of dictionary, so you will extract data with ease.

        do {
            let data: Data = try Data(contentsOf: url as URL)
            let jsonArray: [[String: AnyObject]] = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String: AnyObject]]
            print("json: \(jsonArray)")
    
            for dict in jsonArray {
                let dataName = dict["dataName"] as! String
                print("dataName: \(dataName)")
            }
        }
        catch {
            print("Error: (data: contentsOf: url)")
        }