当前正在努力使用“可降解”。我已经对出现的错误进行了一些搜索,但是我仍然相信构造结构的方式不正确,但对我来说似乎很有意义。
我也尝试过使用可选选项
在我最后发布的错误中,我对Double类型的引用感到困惑。由于我没有任何类型或任何int值,因此他的响应使用了double。
(我还能够使用将数据转换为字典的旧的swift方法来序列化json响应-[String:Any]。但我想使用现代/更新的方法。)
JSON响应
{"NEWS":
[
{
"DATE":"2018-10-13T03:56:06+1000",
"SOURCE":"smh.com.au",
"BLURB":"Assistant Treasurer Stuart Robert says he has repaid $37,975 of \"excess usage charges\" in home internet bills footed by taxpayers.",
"ID":102347,
"TITLE":"Stuart Robert pays back $38,000 in excessive home internet charges"
},
{
"DATE":"2018-10-12T18:00:38+1000",
"SOURCE":"itwire.com",
"BLURB":"The CVC costs set by the NBN Co make it very difficult for ISPs to offer gigabit connections to more than a select band of customers who are willing to sign up in numbers and pay slightly more than other speed tiers, according to one ISP who caters to this type of consumer.",
"ID":102343,
"TITLE":"NBN gigabit connections will remain mostly a pipe dream"},
{
"DATE":"2018-10-12T09:48:43+1000",
"SOURCE":"computerworld.com.au",
"BLURB":"The Department of Home Affairs has rejects calls to include independent judicial oversight of the decision to issue Technical Assistance Notices and Technical Capability Notices as part of proposed legislation intended to tackle police agencies’ inability to access encrypted communications services.",
"ID":102342,
"TITLE":"Home Affairs rejects calls for additional safeguards in ‘spyware’ law"
},
{
"DATE":"2018-10-11T12:16:05+1000",
"SOURCE":"itnews.com.au",
"BLURB":"NBN Co is hoping to “speed up” building works on the fibre-to-the-curb (FTTC) portion of its network as it tries to make up lost ground.",
"ID":102334,
"TITLE":"NBN Co says fibre-to-the-curb build is more complex that it hoped"
},
]
}
代码
struct Root: Decodable {
let news: [News]?
enum CodingKeys: String, CodingKey {
case news = "NEWS"
}
}
struct News: Decodable {
let date: Date
let source, blurb: String
let id: Int
let title: String
enum CodingKeys: String, CodingKey {
case date = "DATE"
case source = "SOURCE"
case blurb = "BLURB"
case id = "ID"
case title = "TITLE"
}
}
序列化
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let dataStr = data else {
return
}
do {
let root = try JSONDecoder().decode(Root.self, from: dataStr) //error is caught here
guard let r = root else { return }
print(r.news)
} catch let err {
print("JSON Error - \(err)")
}
}.resume()
错误
序列化json typeMismatch(Swift.Double,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ NEWS”,intValue:nil),_JSONKey(stringValue:“ Index 0”,intValue:0),intValue:0),CodingKeys( stringValue:“ DATE”,intValue:nil)],debugDescription:“预期对Double进行解码,但找到了一个字符串/数据。”,底层错误:nil))
答案 0 :(得分:3)
这是因为Date的默认编码策略是double(自纪元以来的秒数)。您可以将默认策略更改为iso8061或任何自定义。例如,您可以像这样在解码器中设置日期格式程序:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
答案 1 :(得分:0)
将JSON放入Quicktype中会给我带来一个额外的逗号错误。除非json文件有更多节点?因此,请首先确定。乍一看,我可能是错的,但我认为您必须格式化DATE使其完全匹配。