简体   繁体   English

解码蒸气中的对象数组

[英]decode array of objects in vapor

How can i decode the following json-array (which is part of a http-request) 我如何解码以下json数组(属于http请求的一部分)

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

in swift vapor 3 with the decode function? 在具有解码功能的快速蒸气3中?

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

Your code is pretty close already, only a tiny change is needed: instead of decoding a single User, decode an array of them. 您的代码已经很接近了,只需要进行很小的更改:无需解码单个User,而是解码它们的数组。 Note the square brackets in decode . 注意decode的方括号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM