我使用nickel.rs:
router.get("/api/movies", middleware! { |request, response|
let mut test_movies =
r#"[
{ "title": "Ironman"},
{ "title": "The Walk"},
{ "title": "Paddington"}
]
"#;
let json = Json::from_str(test_movies);
format!("{}", json.unwrap())
});
我想创建 JSON 格式。连接 PostgreSQL 并转换为 JSON 定义的代码如下:
extern crate rustc_serialize;
use rustc_serialize::json::{Json, Parser};
#[derive(RustcDecodable, RustcEncodable)]
struct Movie {
title: String,
}
我尝试选择查询并创建 JSON
router.get("/api/movies", middleware! { |request, response|
let conn = Connection::connect("postgres://postgres@localhost", SslMode::None).unwrap();
let stmt = match conn.prepare("select title from movie") {
Ok(stmt) => stmt,
Err(e) => {
return response.send(format!("Preparing query failed: {}", e));
}
};
let res = match stmt.execute(&[]) {
Ok(v) => println!("Selecting movie was Success."),
Err(e) => println!("Selecting movie failed. => {:?}", e)
};
// ???
// let movies = Json::from_obj(res);
// let movies = request.json_as::<&[Movie]>().unwrap();
// let movies = request.json_as::Vec<Movie>().unwrap();
format!("{}", movies)
});
但是,我不知道如何将结果转换为 JSON。
let conn = conn.clone();
犯错误。
error: no method named `clone` found for type `postgres::Connection` in the current scope
我添加了
use nickel::status::StatusCode;
//use rustc_serialize::json::{Json, Parser};
use rustc_serialize::{json};
json::encode(&movies).unwrap();
是工作。但是返回了null...
最后
我改为execute
并query
使用Vec<Movie>
.
let mut v: Vec<Movie> = vec![];
let movies = &conn.query("select title from movie", &[]).unwrap();
for row in movies {
let movie = Movie {
title: row.get(0),
};
v.push(movie);
}
let json_obj = json::encode(&v).unwrap();
response.set(MediaType::Json);
response.set(StatusCode::Ok);
return response.send(json_obj);
我还定义struct
了类似 Moview 的模型
struct Movie {
// id: i32,
title: String,
}
嗯..麻烦很多。
但是,我还不能conn.clone()
。