devnull
devnull

Reputation: 2862

decoding an array of objects in swift

I have an array of objects

{"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"}}
]}

that I need too fit in struct and then decode in swift. My current code is:

struct Index: Content {

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

}

and the router (using 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)
        }
    }

to summarise all is fine for the first level (total rows and offset are int and properly decoded) but how can I include in my structure the rows: array and assign thee parsed values to it ?

Upvotes: 0

Views: 367

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

You're on the right road, you just need to keep going.

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

Then you define a Row:

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

It's not really clear what a Value is in this context, but just to keep the structure.

struct Value: Decodable {
    var rev: String
}

And that's all.

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

Upvotes: 2

Related Questions