【问题标题】:Decoding JSON data in swift4 with dates在 swift4 中用日期解码 JSON 数据
【发布时间】:2018-01-03 14:57:54
【问题描述】:

我是新手,在理解这一切如何运作时遇到了一些麻烦。

我有这个结构:

struct EventDetail:Decodable {

    let EventName: String
    let EventInformation: String
    let EventStartDate: Date
    let EventEndDate: Date
}

还有这个函数来下载 json:

func downloadJSON(completed: @escaping () -> ()) {

    let url = URL(string: "http://someurl.php")

    URLSession.shared.dataTask(with: url!) { (data, response, error) in

        if error == nil {
            do {


                self.events = try JSONDecoder().decode([EventDetail].self, from: data!)


                DispatchQueue.main.async {
                    completed()
                }
            }catch {
                print(error)
            }
        }
    }.resume()
}

}

这是我得到的 JSON 错误:

JSON 错误 typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), Cosplay_Life.EventDetail.(CodingKeys in _52013DB7ECF3BE1EBFBF83BE6BA8F9E9) , debugDescription: "预期解码 Double 但找到了一个字符串/数据。",底层错误: nil))

如果EventStartDateEventEndDate 是字符串,这一切似乎都有效,但我确实希望将其作为Date,因为稍后我将使用日期字段对数据进行排序。下载的值格式为 "yyyy-MM-dd" eks: "2017-02-25" 我在做什么错?

【问题讨论】:

标签: json swift4


【解决方案1】:

日期是一个 Double,因为它是自纪元以来的毫秒数。

试试这个:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
// Use format appropriate to your JSON String.  This is for ISO-8601
// You MUST account for the milliseconds even if you don't want them 
// or it won't parse properly
dateFormatter.dateFormat = "yy-MM-dd'T'HH:mm:ss.SSS" 

eventDetail.EventStartDate = dateFormatter.date(from: jsonEventStartDateField)!
eventDetail.EventEndDate   = dateFormatter.date(from: jsonEventEndDateField)!

【讨论】:

  • 答案与问题完全无关。 OP 使用 JSONDecoder() 并且日期格式显然是 not ISO8601
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
相关资源
最近更新 更多