我正在尝试从JSON解析一些数据,我已经使用其他API进行了处理,但是现在我有了另一个结构,并且遇到了错误:
线程1:致命错误:“尝试!”表达式意外引发错误: Swift.DecodingError.valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath:[_JSONKey(stringValue:“索引 1“,intValue:1),CodingKeys(stringValue:” evaluation“,intValue: nil)],debugDescription:“预期的Int值,但发现为null。”, 底层错误:nil))
JSON:
{
"restaurants": [
{
"id": 2,
"res_name": "Test",
"res_phone": "Test",
"evaluation": 4,
"created_at": "2019-05-12 22:05:20",
"updated_at": "2019-05-12 22:05:20"
},
{
"id": 3,
"res_name": "Test",
"res_phone": "Test",
"evaluation": null,
"created_at": "2019-05-12 21:46:59",
"updated_at": "2019-05-12 21:46:59"
},
{
"id": 4,
"res_name": "Test",
"res_phone": "Test",
"evaluation": null,
"created_at": "2019-05-13 14:49:20",
"updated_at": "2019-05-13 14:49:20"
}
]
}
我的结构模型:
struct Restaurant: Codable {
let id: Int
let resName, resPhone: String
let evaluation: Int
let createdAt, updatedAt: String
enum CodingKeys: String, CodingKey {
case id
case resName = "res_name"
case resPhone = "res_phone"
case evaluation
case createdAt = "created_at"
case updatedAt = "updated_at"
}
}
我的代码:
Alamofire.request("http://test.tlict.com/public/api/restaurant/show?api_token=\(UserDefaults.standard.string(forKey: "token")!)").responseJSON(completionHandler: { (response) in
print("tokennnnnn isssssssssssssss\(UserDefaults.standard.string(forKey: "token")!) ")
//token
switch response.result {
case .success(let data):
let object = data as! [String : Any]
let result = object["restaurants"] as! [[String : Any]]
let dataCategory = try! JSONSerialization.data(withJSONObject: result, options: [])
self.arrayOfRestaurant = try! JSONDecoder.init().decode([Restaurant].self, from: dataCategory)
DispatchQueue.main.async {
self.myTable.reloadData()
}
case .failure(let error): break
print(error.localizedDescription)
}
})