我正在使用柴油库查询数据库并获取Vec<Bookable>
结构。
#[derive(QueryableByName)]
pub struct Bookable {
#[sql_type = "BigInt"]
pub id: i64,
#[sql_type = "Text"]
pub title: String
}
查询元素时,可以访问结果,但是无法将Vec<Bookable>
转换为json!
宏:
pub fn get_terms(conn: &MysqlConnection) -> Vec<Bookable> {
diesel::sql_query(r#"SELECT title, LAST_INSERT_ID() 'id' from bookable_term;"#)
.load::<Bookable>(conn).expect("Query failed")
}
后来我这样称呼它:
let conn = connect();
let terms = bookable::get_terms(&conn);
json!({ "data": {
"items": terms }
})
问题是如何将术语放入此对象并将整个数组发送到API?我可以像这样将json字符串化:
"items:" &vec!["to", "be", "or", "not", "to", "be"]
但是对于现有的Vec,我会遇到编译器错误。我正在使用Rocket
,因此它提供了一个rocket_contrib::json::JsonValue
,其中包含json!
宏
答案 0 :(得分:0)
首先,您派生结构--
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use rocket_contrib::{json::{Json}};
#[derive(QueryableByName, Deserialize, Serialize)]
pub struct Bookable {
#[sql_type = "BigInt"]
pub id: i64,
#[sql_type = "Text"]
pub title: String
}
然后您可以执行类似的操作-
let conn = connect();
let terms = bookable::get_terms(&conn);
let mut data: Vec<Bookable> = HashMap::new();
data.insert("data", terms);
return Json(Vec<Bookable>);
Json(Vec<Bookable>)
还将响应的内容类型设置为json。