我有一个这样的对象是Dictionary<String,AnyObject>
:
["velocity": 0.0, "constant_b": 0.0, "created_at": 2016-10-10T01:02:04Z, "shot_date": 2016-10-08T00:29:52.596+00:00, "time": 2016-10-10T01:02:04Z, "shot_origin_y": 0.0, "peak_ball_height": 0.0, "shot_origin_x": 0.0, "made": null, "date": 2016-10-10T01:02:04Z, "constant_a": 0.0, "shot_length": 0.0, "ball_position_y": 0.0, "lr": 0.0, "depth": 0.0, "id": 2517999, "clean_make": null, "location_id": 1, "player_id": null, "ball_position_x": 0.0, "entry_angle": 0.0, "constant_c": 0.0]
当像这样传递给我的对象时(这使用GLOSS,一个用于解析JSON对象的cocoapod):
Shot(json: shotJSON)
我在打开一个Optional值时意外地发现nil,但是id显然在那里并且显然是整数。
这是光泽对象:
import Foundation
import Gloss
class Shot: Decodable, FAURequestsDecodable, Equatable{
let id:Int
let velocity:Double?
let time:NSDate?
let shotOriginY:Double?
let shotOriginX:Double?
let shotLength:Double?
let shotDate:NSDate?
let playerId:Int?
let peakBallHeight:Double?
let made:Bool?
let lr:Double?
let locationId:Int?
let entryAngle:Double?
let depth:Double?
let date:NSDate?
let createdAt:NSDate?
let constantC:Double?
let constantB:Double?
let constantA:Double?
let cleanMake:Bool?
let ballPositionY:Double?
let ballPositionX:Double?
let dateFormatter = NSDateFormatter()
//Mark: - Deserialization
required init?(json: JSON){
self.id = ("id" <~~ json)!
self.velocity = "velocity" <~~ json
self.shotOriginY = "shot_origin_y" <~~ json
self.shotOriginX = "shot_origin_x" <~~ json
self.shotLength = "shot_length" <~~ json
self.playerId = "player_id" <~~ json
self.peakBallHeight = "peak_ball_height" <~~ json
self.made = "made" <~~ json
self.lr = "lr" <~~ json
self.locationId = "location_id" <~~ json
self.entryAngle = "entry_angle" <~~ json
self.depth = "depth" <~~ json
self.constantC = "constant_c" <~~ json
self.constantB = "constant_b" <~~ json
self.constantA = "constant_a" <~~ json
self.cleanMake = "clean_make" <~~ json
self.ballPositionY = "ball_position_y" <~~ json
self.ballPositionX = "ball_position_x" <~~ json
dateFormatter.dateFormat = "yyyy-dd-MM'T'HH:mm:ss'Z'"
self.createdAt = Decoder.decodeDate("created_at", dateFormatter: dateFormatter)(json)
self.date = Decoder.decodeDate("date", dateFormatter: dateFormatter)(json)
self.time = Decoder.decodeDate("time", dateFormatter: dateFormatter)(json)
dateFormatter.dateFormat = "yyyy-dd-MM'T'HH:mm:ss.SSS"
self.shotDate = Decoder.decodeDate("shot_date", dateFormatter: dateFormatter)(json)
}
}