简体   繁体   English

如何使用 Vapor 为我的叶模板获取 json 文件以显示数据?

[英]How can I fetch a json file using Vapor for my leaf template to show the data?

I have a JSON hosted somewhere and I want to fetch the content, put it in a context for my leaf template to read.我在某处托管了一个 JSON,我想获取内容,将其放在上下文中供我的叶模板读取。

However, I cannot make it work.但是,我无法让它工作。 I get the code to compile, but I get an error in the localhost我得到了要编译的代码,但在本地主机中出现错误

{"error":true,"reason":"Unsupported Media Type"}

Can somebody help me please.有人可以帮帮我吗? Happy holidays for all.祝大家节日快乐。

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

Model模型

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

This error is because the decode is failing to identify all the fields in your JSON to match against those defined in Listing and/or the array of such objects.此错误是因为解码无法识别 JSON 中的所有字段以匹配Listing中定义的字段和/或此类对象的数组。 The filenames must match those in the JSON exactly - ie case-sensitive and every field in the structure/model must exist in the JSON.文件名必须与 JSON 中的文件名完全匹配——即区分大小写,并且结构/模型中的每个字段都必须存在于 JSON 中。 Additional fields in the JSON that are not needed/included in the structure/model are fine. JSON 中不需要/不包含在结构/模型中的其他字段都可以。

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

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