Dominik
Dominik

Reputation: 101

decode array of objects in vapor

How can i decode the following json-array (which is part of a http-request)

[ 
  { "id": 0, "name": "darth maul" }, 
  { "id": 1, "name": "darth sidious" } 
]

in swift vapor 3 with the decode function?

vapor code:

struct User: Content {
    var id: Int
    var name: String
}

router.put("user") { request -> Future<HTTPStatus> in
    return try request.content.decode(User.self).map({ (user) -> (HTTPStatus) in
        // process ...
        return .ok
    })
}

Upvotes: 2

Views: 1364

Answers (1)

vzsg
vzsg

Reputation: 2896

Your code is pretty close already, only a tiny change is needed: instead of decoding a single User, decode an array of them. Note the square brackets in decode.

router.put("user") { request -> Future<HTTPStatus> in
    return try request.content.decode([User].self).map({ (users) -> (HTTPStatus) in
        // process ...
        return .ok
    })
}

Upvotes: 4

Related Questions