我的 REST 在 Array 之后返回,并且只有一项。
{
"Table1": [
{
"Id": 1,
"ClauseNo": "2-111",
"Title": "Testing Title",
"URL": "http://www.google.com",
}
]
}
我正在尝试使用 Codable 如下:
struct Clause: Codable {
var Id: Int
var ClauseNo: String
var Title: String
var URL: String
}
以下代码我做错了什么?
func parse(json: Data) -> Clause {
var clause: Clause?
if let jsonClause = try? JSONDecoder().decode([Clause].self, from: json) {
clause = jsonClause
}
return clause!
}
正如我上面提到的,我只有 1 个项目,不超过这个。
这是一个很常见的错误,你忽略了根对象
struct Root : Decodable {
private enum CodingKeys : String, CodingKey { case table1 = "Table1" }
let table1 : [Clause]
}
struct Clause: Decodable {
private enum CodingKeys : String, CodingKey { case id = "Id", clauseNo = "ClauseNo", title = "Title", url = "URL" }
let id: Int
let clauseNo: String
let title: String
let url: URL
}
...
func parse(json: Data) -> Clause? {
do {
let result = try JSONDecoder().decode(Root.self, from: json)
return result.table1.first
} catch { print(error) }
return nil
}
旁注:如果发生错误,您的代码会可靠地崩溃
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句