【发布时间】:2020-01-22 18:50:46
【问题描述】:
我正在进行 api 调用并尝试使用我的JSONDecoder(),但它一直跳到我的位置。我该如何解决这个问题?或者其他人看到有什么问题吗?
do{
print("decoding")
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let commoditiesList = try decoder.decode([HPPluCodeAdd].self, from: data!)
print(commoditiesList)
self.harvestCommodities = commoditiesList
DispatchQueue.main.async {
self.AddHarvestPlanPluCodeTable.reloadData()
print("fin")
}
}catch _{
print("error")
}
我得到的数据:
[
{
"cases_per_week_avg": 0,
"target": 1200,
"pounds_per_case": 35,
"repeat_harvest": true,
"cases_per_week": "0",
"lbs_per_week": "0",
"id": 14,
"acres": 800,
"plu_code": 12188,
"active": true,
"options": 1,
"plant_days": 80,
"plu_code_commodity": "Organic Cabbage",
"plu_code_variety": "Green",
"cases_per_pallette": 42,
"harvest_week_count": 1,
"pounds_per_acre": 32767
},
{
"cases_per_week_avg": 0,
"target": 0,
"pounds_per_case": 20,
"repeat_harvest": true,
"cases_per_week": "0",
"lbs_per_week": "0",
"id": 20,
"acres": 800,
"plu_code": 12187,
"active": true,
"options": 1,
"plant_days": 80,
"plu_code_commodity": "Organic Broccoli",
"plu_code_variety": "",
"cases_per_pallette": 48,
"harvest_week_count": 1,
"pounds_per_acre": 16000
}]
我的结构:
struct HPPluCodeAdd : Decodable{
var id : Int
var commodity: String
var casesPerWeekAvg: Int
var repeatHarvest: Int
var casesPerWeek: Double
var lbsPerWeek :Double
var acres : Int
var pluCode : Int
var active :Bool
var options: Int
var plantDays: Int
var pluCodeCommodity: String
var pluCodeVariety: String
var casesPerPalette: Int
var harvestWeekCount : Int
var poundsPerAcre: Int
var poundsPerCase : Int
}
【问题讨论】:
-
而不是无意义的文字字符串
"error"打印error实例,它告诉你出了什么问题。乍一看,我发现了两个错误。 -
正如 vadian
} catch { print(error) }所提到的 -
知道了,谢谢!
标签: json swift xcode jsondecoder