2

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

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Alex
  • 715
  • 5
  • 14
  • If you have a `struct Response { items: Vec }` where `Bookable` and `Response` impl `serde::Deserialize` (e.g. via a derive) you should be able to return a `rocket_contrib::json::Json` right away. – user2722968 May 17 '19 at 11:06

1 Answers1

0

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.

Abhay PS
  • 4,015
  • 5
  • 25
  • 32