[英]How can I fetch a json file using Vapor for my leaf template to show the data?
我在某處托管了一個 JSON,我想獲取內容,將其放在上下文中供我的葉模板讀取。
但是,我無法讓它工作。 我得到了要編譯的代碼,但在本地主機中出現錯誤
{"error":true,"reason":"Unsupported Media Type"}
有人可以幫幫我嗎? 祝大家節日快樂。
struct WebsiteController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
routes.get(use: indexHandler)
}
func indexHandler(_ req: Request) -> EventLoopFuture<View> {
return req.client.get("https://streeteasydaily.s3.us-west-2.amazonaws.com/streeteasy1.json").flatMap { res in
do {
let json = try res.content.decode([Listing].self)
print(json[0].photos[0])
let context = IndexContext(title: "Homepage", listings: json)
return try req.view.render("index", context)
} catch {
// Handle error
print("cayo en error")
return req.eventLoop.makeFailedFuture(error)
}
}
}
}
struct IndexContext: Encodable {
let title: String
let listings: [Listing]
}
模型
final class Listing: Model {
static let schema = "listings" //basically the table name
@ID
var id: UUID?
@Field(key: "address")
var address: String
@Field(key: "description")
var description: String
@Field(key: "photos")
var photos: [String]
init() {}
//to initialize the db
init(id: UUID? = nil, address: String, description: String, photos: [String]) {
self.id = id
self.address = address
self.description = description
self.photos = photos
}
}
//to make acronym conform to CONTENT, and use it in Vapor
extension Listing: Content {}
此錯誤是因為解碼無法識別 JSON 中的所有字段以匹配Listing
中定義的字段和/或此類對象的數組。 文件名必須與 JSON 中的文件名完全匹配——即區分大小寫,並且結構/模型中的每個字段都必須存在於 JSON 中。 JSON 中不需要/不包含在結構/模型中的其他字段都可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.