简体   繁体   中英

How to convert Vec to JsonValue in Rust

I am querying my database and getting an Vec<Bookable> struct, using diesel library.

#[derive(QueryableByName)]
pub struct Bookable {
  #[sql_type = "BigInt"]
  pub id: i64,
  #[sql_type = "Text"]
  pub title: String
}

When I query the elements, I can access the result, but it's not possible to convert the Vec<Bookable> to json! macro:

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")
}

And later I call it this way:

  let conn = connect();
  let terms = bookable::get_terms(&conn);
  json!({ "data": {
    "items": terms }
  })

The question is how to put the terms into this object and send the whole array to the API? I can stringify a json like this:

"items:" &vec!["to", "be", "or", "not", "to", "be"]

But when it comes to an existing Vec I get compiler error. I am using Rocket so it provides a rocket_contrib::json::JsonValue which holds json! macro

First, you derive your struct like -

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
}

Then you can do something like -

 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>) will also set the content-type as json for the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM