2

我正在使用蒸汽的客户端来获取获取请求。

func sendGetRequest(req: Request) throws -> Future<Response> {
    let client = try req.make(FoundationClient.self)
    return client.get("http://example.vapor.codes/json", headers: ["Accept-Language" : "ar"])
        .map(to: Response.self, { clientResponse in
        let response = req.makeResponse()
        response.http.status = clientResponse.http.status
        response.http.body = clientResponse.http.body
        return response
    })
}

这将返回所有 json 数据,我想过滤它以仅返回 2 个属性,例如在这种情况下 (dict,number)

我已经为数据创建了一个模型

struct ExampleData: Codable {
  //  var array : [Int]
    var dict : [String : String]
    var number : Int
 //   var string : String
}

该函数希望我返回一个 Future<Response>,但如果我将其更改为 Future<ExampleData> 并将映射设置为 .map(to: ExampleData.self ..)

我明白了

无法将“响应”类型的返回表达式转换为返回类型“TodoController.ExampleData”

4

1 回答 1

2

我想到了

func sendGetRequest(req: Request) throws -> Future<ExampleData> {
    let client = try req.make(Client.self)
    let ans =  client.get("http://example.vapor.codes/json", headers: ["Accept-Language" : "ar"]).flatMap { exampleResponse in
        return try exampleResponse.content.decode(ExampleData.self)
    }

    return ans
}
于 2018-06-16T15:24:44.377 回答