hi我想检索json数据,json数据就像这个
"items":[
{
"date_for":"2018-11-11",
"fajr":"5:28 am",
"shurooq":"6:37 am",
"dhuhr":"11:52 am",
"asr":"2:40 pm",
"maghrib":"5:06 pm",
"isha":"6:15 pm"
}
],
然后我让JSONDecoder可以解码如下:
struct PrayerModel: Decodable {
var items: [Items]
}
struct Items: Decodable {
var fajr: String
var dhuhr: String
var asr: String
var maghrib: String
var isha: String
init(dictionary: [String: String]) {
self.fajr = dictionary["fajr"] ?? ""
self.dhuhr = dictionary["dhuhr"] ?? ""
self.asr = dictionary["asr"] ?? ""
self.maghrib = dictionary["maghrib"] ?? ""
self.isha = dictionary["isha"] ?? ""
}
}
然后我制作了一个对象来存储可解码数据:
struct Prayer {
var prayerName: String
var prayerIcon: UIImage
var prayerTime: String
init(prayerName: String, prayerIcon: UIImage, prayerTime: String) {
self.prayerName = prayerName
self.prayerIcon = prayerIcon
self.prayerTime = prayerTime
}
}
并使用URLSession检索:
do {
let prayerData = try JSONDecoder().decode(PrayerModel.self, from: data)
prayerData.items.forEach({ (item) in
let isya = Prayer(prayerName: "Isya", prayerIcon: #imageLiteral(resourceName: "Clear"), prayerTime: item.isha)
self.prayers.append(contentsOf: [shubuh, dzuhur, ashar, maghrib, isya])
})
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch let decodeErr {
print("Failed to decode:", decodeErr)
}
我得到了错误
解码失败:dataCorrupted(Swift。DecodingError.Context(codingPath:[],debugDescription:"给定的数据不是有效的JSON。",underlyingError:可选(Error Domain=NSCocoaErrorDomain Code=3840(JSON文本没有以数组或对象开头,并且没有设置允许片段的选项。"UserInfo={NSDebugDescription=JSON文本未以数组或对象开头,并且未设置允许片段的选项。}((
我的代码有什么问题,有人可以帮忙吗?
正如我在评论中提到的那样,json消息是不正确的,我添加了{},它运行良好。
{"项目":[{
"date_for":"2018-11-11","fajr":"5:28 am","shurooq":"早上6:37","dhuhr":"上午11:52","asr":"下午2:40","maghrib":"下午5:06","isha":"下午6:15">
}]}
如果您不想使用json消息中的所有元素,则不必将它们包括在内,我从Items
中删除了init()
方法,因为它没有被使用。
struct Items: Decodable {
var fajr: String
var dhuhr: String
var asr: String
var maghrib: String
var isha: String
}
然后它与以下代码完美配合
let str = "{"items":[{"date_for":"2018-11-11","fajr":"5:28 am","shurooq":"6:37 am","dhuhr":"11:52 am","asr":"2:40 pm","maghrib":"5:06 pm","isha":"6:15 pm"}]}"
do {
if let data = str.data(using: .utf8) {
let prayerData = try JSONDecoder().decode(PrayerModel.self, from: data)
for item in prayerData.items {
print(item)
}
}
} catch let decodeErr {
print("Failed to decode:", decodeErr)
}
如果您想在JSON中使用可解码原型,那么than变量应该具有完全相同的名称,并包括具有相同位置的所有项。
试试这个:
var date_for: String
var fajr: String
var shurooq: String
var dhuhr: String
var asr: String
var maghrib: String
var isha: String
init(dictionary: [String: String]) {
self.date_for = dictionary["date_for"] ?? ""
self.fajr = dictionary["fajr"] ?? ""
self.shurooq = dictionary["shurooq"] ?? ""
self.dhuhr = dictionary["dhuhr"] ?? ""
self.asr = dictionary["asr"] ?? ""
self.maghrib = dictionary["maghrib"] ?? ""
self.isha = dictionary["isha"] ?? ""
}