解码 swift 中的对象数组

decoding an array of objects in swift

我有一个对象数组

{"total_rows":5,"offset":0,"rows":[
{"id":"index","key":"index","value":{"rev":"4-8655b9538706fc55e1c52c913908f338"}},
{"id":"newpage","key":"newpage","value":{"rev":"1-7a27fd343ff98672236996b3fe3abe4f"}},
{"id":"privacy","key":"privacy","value":{"rev":"2-534b0021f8ba81d09ad01fc32938ce15"}},
{"id":"secondpage","key":"secondpage","value":{"rev":"2-65847da61d220f8fc128a1a2f1e21e89"}},
{"id":"third page","key":"third page","value":{"rev":"1-d3be434b0d3157d7023fca072e596fd3"}}
]}

我需要太适合结构,然后在 swift 中解码。我当前的代码是:

struct Index: Content {

    var total_rows: Int
    var offset: Int
   // var rows: [String: String] // I don't really know what I am doing here 

}

和路由器(使用 vapor)

router.get("/all") { req -> Future<View> in
        let docId = "_all_docs"
        print(docId)
        let couchResponse = couchDBClient.get(dbName: "pages", uri: docId, worker: req)
        guard couchResponse != nil else {
            throw Abort(.notFound)
        }

        print("one")
        return couchResponse!.flatMap { (response) -> EventLoopFuture<View> in
            guard let data = response.body.data else { throw Abort(.notFound) }

            print(data)

            let decoder = JSONDecoder()
            let doc = try decoder.decode(Index.self, from: data)

            let allDocs = Index(
                total_rows: doc.total_rows,
                offset: doc.offset
                //rows: doc.rows
            )
            print("test after allDocs")
            return try req.view().render("index", allDocs)
        }
    }

总而言之,对于第一级来说一切都很好(总行数和偏移量是 int 并且已正确解码)但是我如何在我的结构中包含 rows: array 并将解析后的值分配给它?

你走在正确的道路上,你只需要继续前进。

struct Index: Decodable {
    var total_rows: Int
    var offset: Int
    var rows: [Row]
}

然后你定义一个行:

struct Row: Decodable {
    var id: String
    var key: String
    var value: Value
}

在此上下文中,值是什么并不是很清楚,只是为了保持结构。

struct Value: Decodable {
    var rev: String
}

仅此而已。

let index = try JSONDecoder().decode(Index.self, from: jsonData)