[英]How to convert Vec to JsonValue in Rust
我正在查询我的数据库并获得一个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 }
})
问题是如何将terms放入这个对象,并将整个数组发送给API? 我可以像这样将 json 字符串化:
"items:" &vec!["to", "be", "or", "not", "to", "be"]
但是当涉及到现有的 Vec 时,我会收到编译器错误。 我正在使用Rocket
因此它提供了一个rocket_contrib::json::JsonValue
的rocket_contrib::json::JsonValue
json!
宏
首先,你派生你的结构 -
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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.