如何在 Rust 中将 Vec 转换为 JsonValue

How to convert Vec to JsonValue in Rust

我正在使用 diesel 库查询我的数据库并获得一个 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!

首先,你像 -

一样派生你的结构
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。