Swift JSONSerialization.jsonObject错误

时间:2016-11-07 01:16:02

标签: json swift error-handling nsmutablearray jsonserializer

我环顾四周但是我没有找到答案来解决这个一直困扰着我的错误。我尝试添加“as!NSMutableArray”,但这给了我另一个错误。关于如何修复它的任何想法?我将我的项目从Objective-C转换为Swift,所以希望代码很好我现在有20多个错误我现在已经失误了3个错误。谢谢。

错误消息:

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

code error picture

从服务器检索数据的代码

// 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()
}

1 个答案:

答案 0 :(得分:3)

jsonObject函数将返回Any类型的值,但jsonArray的类型为NSMutableArray。如果出现问题,此函数将抛出错误,在其前面加上try关键字。根据我的经验,让我们将jsonArray的类型更改为字典数组,这样您就可以轻松提取数据。

    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)")
    }