我尝试使用Swift 3,Gloss 1.1和Alamofire 4.0从webrequest解码json对象: json响应如下:
{
"code": "0",
"message": "OK.",
"data": [
{
"timestamp": 1480885860,
"open": 10.99
},
{
"timestamp": 1480886040,
"open": 11
}
]
}
我的json Decodables是以下两个:
struct ResponseJsonModel : Decodable {
let code : Int
let message : String
let data : [MarketPriceJsonModel]?
// <~~
init?(json: JSON) {
guard let codeInt : Int = "code" <~~ json else {
print("code unwrapping failed in guard")
return nil
}
guard let messageStr : String = "message" <~~ json else {
print("message unwrapping failed in guard")
return nil
}
self.code = codeInt
self.message = messageStr
self.data = "data" <~~ json
}
}
struct MarketPriceJsonModel : Decodable {
let timestamp : NSDate
let open : Double
init?(json: JSON) {
guard let timestampInt : Int = "timestamp" <~~ json else {
print("timestamp unwrapping failed in guard")
return nil
}
guard let open : Double = "open" <~~ json else {
print("open price unwrapping failed in guard")
return nil
}
self.timestamp = NSDate(timeIntervalSince1970: Double(timestampInt))
self.open = open
}
}
我是Gloss的新手,并且不明白为什么我的decodable-Object的初始化失败了。
Alamofire.request(url).validate().responseJSON { response in
switch response.result {
case .success:
guard let value = response.result.value as? JSON,
let responseModel = ResponseJsonModel(json: value) else {
print("responseModel failed")
return
}
print(responseModel.message)
case .failure(let error):
print(error)
}
}
代码的输出是
代码展开失败后卫
responseModel失败
但为什么?
当我在init?()中添加断点并查看调试区域中的json-variable时,请求看起来没问题,但解析失败。
有没有办法在出现故障时获得更好的异常消息?
任何意见都赞赏。