Vapor`client.get`,转换并返回json

时间:2017-01-26 07:28:50

标签: json swift vapor

我正在尝试从其他Web服务获取数据,然后对其进行转换并将其返回。我在文档中找到了Spotify示例,但我不确定如何返回JSON的一部分。

drop.get("music") { request in
    guard let query = request.data["q"]?.string else {
        throw Abort.badRequest
    }

    let result = try drop.client.get(
        "https://api.spotify.com/v1/search",
        query: ["type": "artist", "q": query]
    )

    return result.data["artists"]?.array
}

我尝试构建时遇到此错误:error: return expression of type '[Polymorphic]?' does not conform to 'ResponseRepresentable'

1 个答案:

答案 0 :(得分:2)

您的result.dataContent,可能是任何内容。你需要首先确定它的JSON,然后你可以返回它。

drop.get("music") { request in
    guard let query = request.data["q"]?.string else {
        throw Abort.badRequest
    }

    let result = try drop.client.get(
        "https://api.spotify.com/v1/search",
        query: ["type": "artist", "q": query]
    )

    guard
        result.status == .ok,
        let artistsJson = result.data["artists"] as? JSON
    else {
        throw Abort.serverError
    }

    return artistsJson
}