在光泽和Alamofire解析JSON数据迅速
问题描述:
我想一个JSON对象从WebRequest的与斯威夫特3解码,光泽1.1和Alamofire 4.0: JSON响应看起来是这样的:在光泽和Alamofire解析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
}
}
我是新来的光泽度和不明白为什么我的解码-对象的initalize失败。
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变量时,请求看起来不错,但解析失败。
有没有办法的情况下,一些未能获得更好的异常信息?
任何输入赞赏。
答
好的,问题解决了。这是web服务的错误配置。 正如你看到的,代码属性的JSON的反应是:
"code": "0",
这种格式显然代表了一个字符串,为此我的后卫解析转换成int会失败。 要解决这个问题,我找到了两种可能的方法。
选项1:要么改变JSON响应于:
"code": 0,
(值已没有更多的周围引号)。这可能是最好的解决方案,因为它修复了web服务的错误数据类型,但它需要完全控制服务的代码库。
选项2:只是将json响应解析为一个字符串,然后强制展开为一个Int工作。对于这个解决方案,web服务将保持不变。
guard let codeStr : String = "code" <~~ json else {
print("code unwrapping failed in guard")
return nil
}
self.code = Int(codeStr)!