我使用此调用创建了一个 JSON 数组:
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [Any] else {
print("This is not JSON!!!")
return
}
我尝试从数组中的 JSON 对象获取元素,以使用以下代码显示它们:
struct sWidget: Codable{
var createdBy: String
var createdDate: Date
var status: String
var widgetNumber: String
var updatedBy: String
var updatedDate: Date
}
do {
let decoder = JSONDecoder()
for (index, value) in json.enumerated() {
let currentWidget = try decoder.decode(sWidget.self, from: json[index] as! Data)
let currentNum = currentWidget.widgetNumber
//print(currentNum)
widgetNums.append(currentNum)
}
}
catch {
print("decoding error")
}
代码可以编译,但是当我运行它时,我在输出中收到此错误:
Could not cast value of type '__NSDictionaryM' (0x1063c34f8) to 'NSData' (0x1063c1090). 2018-08-09 09:41:02.666713-0500 TruckMeterLogScanner[14259:1223764] Could not cast value of type '__NSDictionaryM' (0x1063c34f8) to 'NSData' (0x1063c1090).
我仍在调查,但任何提示都会有帮助。
最佳答案
您是否尝试过像上面提到的那样获取对象?因为我看到你正在使用 Codable。实际上,获取非常简单。
let yourObjectArray = JSONDecoder().decode([sWidget].self, data: json as! Data)
可能这一行可能有问题,但您可以用一行获取它们。
关于json - 使用 Swift Decoder 从 JSON 数组中提取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51769882/