我的REST返回以下数组,并且只有一个。
{
"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!
}
如上所述,我只有一件商品。
答案 0 :(得分: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
}
侧面说明:如果发生错误,您的代码将可靠地崩溃
答案 1 :(得分:-1)
我倾向于处理以下情况:
struct Table1 : Codable {
var clauses: [Clause]
struct Clause: Codable {
let Id: Int // variable names should start with a lowercase
let ClauseNo: String // letter :)
let Title: String
let URL: String
}
}
然后,在解码时,您将得到一个想要第一个元素的表,例如:
if let jsonTable = try? JSONDecoder().decode(Table1.self, from: json) {
clause = jsonTable.clauses[0]
}