将JSON(日期)解析为Swift

Are*_*tas 6 parsing json ios swift

我在Swift中的应用程序中返回了JSON,并且有一个字段可以返回给我一个日期.当我参考这些数据时,代码给了我类似"/ Date(1420420409680)/"的内容.如何将其转换为NSDate?在Swift中,我已经使用Objective-C测试了示例,但没有成功.

Mar*_*n R 9

这与Microsoft的ASP.NET AJAX使用的日期的JSON编码非常相似,后者在JavaScript和.NET的JavaScript Object Notation(JSON)简介中有所描述:

例如,Microsoft的ASP.NET AJAX既不使用所描述的约定.相反,它将.NET DateTime值编码为JSON字符串,其中字符串的内容为/ Date(ticks)/,其中ticks表示自纪元(UTC)以来的毫秒数.所以1989年11月29日凌晨4:55:30,UTC编码为"\/Date(628318530718)\ /".

唯一的区别是你有格式/Date(ticks)/ 而不是\/Date(ticks)\/.

您必须提取括号之间的数字.将其除以1000可得出自1970年1月1日以来的秒数.

以下代码显示了如何完成此操作.它被实现为"可用的便利初始化器",用于NSDate:

extension NSDate {
    convenience init?(jsonDate: String) {

        let prefix = "/Date("
        let suffix = ")/"
        // Check for correct format:
        if jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) {
            // Extract the number as a string:
            let from = jsonDate.startIndex.advancedBy(prefix.characters.count)
            let to = jsonDate.endIndex.advancedBy(-suffix.characters.count)
            // Convert milliseconds to double
            guard let milliSeconds = Double(jsonDate[from ..< to]) else {
                return nil
            }
            // Create NSDate with this UNIX timestamp
            self.init(timeIntervalSince1970: milliSeconds/1000.0)
        } else {
            return nil
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例用法(包含您的日期字符串):

if let theDate = NSDate(jsonDate: "/Date(1420420409680)/") {
    print(theDate)
} else {
    print("wrong format")
}
Run Code Online (Sandbox Code Playgroud)

这给出了输出

2015-01-05 01:13:29 +0000

更新Swift 3(Xcode 8):

extension Date {
    init?(jsonDate: String) {

        let prefix = "/Date("
        let suffix = ")/"

        // Check for correct format:
        guard jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) else { return nil }

        // Extract the number as a string:
        let from = jsonDate.index(jsonDate.startIndex, offsetBy: prefix.characters.count)
        let to = jsonDate.index(jsonDate.endIndex, offsetBy: -suffix.characters.count)

        // Convert milliseconds to double
        guard let milliSeconds = Double(jsonDate[from ..< to]) else { return nil }

        // Create NSDate with this UNIX timestamp
        self.init(timeIntervalSince1970: milliSeconds/1000.0)
    }
}
Run Code Online (Sandbox Code Playgroud)

例:

if let theDate = Date(jsonDate: "/Date(1420420409680)/") {
    print(theDate)
} else {
    print("wrong format")
}
Run Code Online (Sandbox Code Playgroud)