我有一个对象数组
struct Index: Content {
var total_rows: Int
var offset: Int
// var rows: [String: String] // I don't really know what I am doing here
}
我需要太适合结构,然后迅速解码。我当前的代码是:
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)
}
}
和路由器(使用蒸气)
fmt.Println(windowspathenv.Resolve("%USERPROFILE%/Documents"))
// C:\Users\YourName\Documents
总结一下,对于第一级来说一切都很好(总行和偏移量是int并已正确解码),但是如何在我的结构中包括row:数组并为其分配解析后的值呢?
答案 0 :(得分:2)
您在正确的道路上,只需要继续前进即可。
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)