如何使用镍模板返回JSON文件?

时间:2016-09-12 06:21:54

标签: json rust nickel

我正在尝试使用Nickel模板返回JSON文件。我发现了一些返回JSON响应并修改它的API示例代码:

myErrorView = [[ErrorView alloc]initWithdelegate:self ForView:self.view];

extern crate rustc_serialize; #[macro_use] extern crate nickel; use nickel::{Nickel, HttpRouter, JsonBody}; use nickel::mimes::MediaType; use nickel::status::*; use rustc_serialize::json; use std::collections::HashMap; #[derive(RustcDecodable, RustcEncodable)] struct Person { firstname: String, lastname: String, } fn main() { let mut server = Nickel::new(); server.get("/post", middleware! { |request, mut response| let person: Person = Person { firstname: "firstName ".to_string(), lastname: "lastName".to_string()}; let mut p: Vec<Person> = vec![]; p.push(person); let json_data = json::encode(&p).unwrap(); let mut data_result = "{\"status\": 200, \"data\":".to_owned(); data_result.push_str(&json_data.to_string()); data_result.push_str("}"); response.set(StatusCode::Ok); response.set(MediaType::Json); format!("{}", data_result) }); server.get("/json", middleware! { |_, response| let mut data = HashMap::new(); data.insert("name", "user"); return response.render("app/views/temp.tpl", &data); // template source // //{name: {{name}}} // }); server.listen("127.0.0.1:6767"); } 返回此JSON:

/post

{ "status": 200, "data": [{ "firstname": "firstName ", "lastname": "lastName" ]} 会返回此文字:

/json

如何使用模板返回JSON文件?

1 个答案:

答案 0 :(得分:0)

它实际上会返回

{name: user}

您需要做的只是在其他处理程序中添加已经拥有response.set(MediaType::Json);

#[macro_use]
extern crate nickel;

use nickel::{Nickel, HttpRouter};
use nickel::mimes::MediaType;
use std::collections::HashMap;

fn main() {
    let mut server = Nickel::new();

    server.get("/json", middleware! { |_, mut response| {
        let mut data = HashMap::new();
        data.insert("name", "user");
        response.set(MediaType::Json);
        return response.render("app/views/temp.tpl", &data);
    }});

    server.listen("127.0.0.1:6767");
}

现在,这可能不是一个的想法。通过字符串连接创建结构化格式(CSV,JSON,XML等)通常会出现格式错误的文档或不正确的数据转发问题。