使用SwiftyJSON反序列化NSDate [英] Use SwiftyJSON to deserialize NSDate

查看:264
本文介绍了使用SwiftyJSON反序列化NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSON日期反序列化为NSDate的最佳方法是什么?使用SwiftyJSON实例?

What is the best way to deserialize a JSON date into an NSDate instance using SwiftyJSON?

是仅将stringValueNSDateFormatter一起使用,还是SwiftyJSON有内置的日期API方法?

Is it to just use stringValue with NSDateFormatter or is there a built in date API method with SwiftyJSON?

推荐答案

听起来好像SwiftyJSON中没有内置NSDate支持,但是您可以使用自己的便捷访问器来扩展JSON类.

It sounds like NSDate support isn't built in to SwiftyJSON, but you can extend the JSON class with your own convenience accessors.

以下代码改编自此GitHub问题.

extension JSON {
    public var date: NSDate? {
        get {
            if let str = self.string {
                return JSON.jsonDateFormatter.dateFromString(str)
            }
            return nil
        }
    }

    private static let jsonDateFormatter: NSDateFormatter = {
        let fmt = NSDateFormatter()
        fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        fmt.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        return fmt
    }()
}

示例:

let j = JSON(data: "{\"abc\":\"2016-04-23T02:02:16.797Z\"}".dataUsingEncoding(NSUTF8StringEncoding)!)

print(j["abc"].date)  // prints Optional(2016-04-23 02:02:16 +0000)

您可能需要调整日期格式化程序以获取您自己的数据;有关更多示例,请参见此问题.另请参见有关JSON中日期格式的问题.

You might need to tweak the date formatter for your own data; see this question for more examples. Also see this question about date formatting in JSON.

这篇关于使用SwiftyJSON反序列化NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆