【问题标题】:How to convert Vec to JsonValue in Rust如何在 Rust 中将 Vec 转换为 JsonValue
【发布时间】:2019-05-17 10:03:04
【问题描述】:

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

【问题讨论】:

  • 如果你有一个struct Response { items: Vec&lt;Bookable&gt; },其中BookableResponse impl serde::Deserialize(例如通过派生)你应该能够立即返回一个rocket_contrib::json::Json&lt;Response&gt;

标签: json rust rust-rocket


【解决方案1】:

首先,你将你的结构派生出来 -

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&lt;Bookable&gt;) 还会将响应的内容类型设置为 json。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2017-05-01
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多