class DJStockPoolDragonHeadItemsModel: Codable {
var isBusiness:Int?
var blockName:String?
//入選價格
var price:Double?
var id: Int?
var blockMarket:Int?
//股票名字
var name:String?
//是否是龍頭
var isCock:Int?
//入選時間
var time: String?
var smallMarket:Int?
var stockStatusImg:String?
//股票池名稱
var typeName:String?
var market:Int?
var blockCode:String?
//股票代碼
var code:String?
var customDate:int?
var blockID:String?
//最高漲幅
var maxRise:Double?
var isBsiness:Int?
}
market 字段后臺起先返回的是int,突然有一天返回了string,導(dǎo)致于IOS這邊拿不到model數(shù)據(jù)經(jīng)過排查查看解析是用swift提供的解析
if let objArr = obj as? [[String:Any]] {
let models = objArr.toObjct(type: [DJStockPoolDragonHeadItemsModel].self)
recvHandler(models)
} else {
recvHandler(nil)
}
/// 轉(zhuǎn)model
/// - Parameter type: type
/// - Returns: model
func toObjct<T>(type:T.Type) -> T? where T : Decodable {
if let obj = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) {
let decoder = JSONDecoder()
if let data = try? decoder.decode(T.self, from: obj) {
return data
}
}
return nil
}
為了弄清原因?qū)⒋a修改如下
/// 轉(zhuǎn)model
/// - Parameter type: type
/// - Returns: model
func toObjct<T>(type:T.Type) -> T? where T : Decodable {
if let obj = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) {
let decoder = JSONDecoder()
if let data = try? decoder.decode(T.self, from: obj) {
return data
}
var data:Any?
do {
data = try! decoder.decode(T.self, from: obj)
} catch {
print(error)
}
}
return nil
}
運行后查看
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "customDate", intValue: nil)], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil)): file _Test/ArrayExtensions.swift, line 44
2023-10-28 10:12:31.679135+0800 -Test[4259:80177] Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "customDate", intValue: nil)], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil)): file _Test/ArrayExtensions.swift, line 44
報錯信息顯示 CodingKeys(stringValue: "customDate", intValue: nil)
查看后臺原始數(shù)據(jù)
![73AD650AE3265779FB0CC0F066EAFA2E.png](https://upload-images.jianshu.io/upload_images/1192250-0d0606e6506d465f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![73ad650ae3265779fb0cc0f066eafa2e.png](https://upload-images.jianshu.io/upload_images/1192250-c297b9b8ce92c769.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
竟然是string類型旱捧,好吧我改氢拥。改完string后順利拿到了數(shù)據(jù)