gpt4 book ai didi

json - Swift JSONSerialization.jsonObject 错误

转载 作者:行者123 更新时间:2023-11-28 11:01:31 25 4
gpt4 key购买 nike

我环顾四周,但没有找到解决这个困扰我的错误的答案。我尝试添加一个“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()
}

最佳答案

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

关于json - Swift JSONSerialization.jsonObject 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40456470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com