在 swift 中遇到 JSON 解析问题

Facing problem with JSON parsing in swift

我的REST returns下面的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
}

旁注:如果发生错误,您的代码会可靠地崩溃

我倾向于这样处理这些场景:

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
    }
}

然后当你解码时,你最终得到一个 table,你想要第一个元素,比如:

if let jsonTable = try? JSONDecoder().decode(Table1.self, from: json) {
   clause = jsonTable.clauses[0]
}