2

I'm trying to return Json data with a rocket handler. I've seen many other posts with the same issue, where the solution for basically everyone where that they hadn't implemented serde::Deserialize/serde::Serialize. Does anyone have a solution?

rocket_contrib docs

use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct MyStruct;

pub fn get_timestamps(pool: &State<Pool>) -> Json<MyStruct> {
    ^^^^^^^^^^^^^^ the trait `Responder<'_, '_>` is not implemented for `rocket_contrib::json::Json<MyStruct>`

Cargo.toml

[dependencies]
rand = "0.8.4"
bytes = "1"
mysql = "*"
dotenv = "0.15.0"
serde = { version = "1", features = ["derive"] }
serde_derive = "1.0.127"
diesel = "1.4.7"
chrono = "0.4.19"
serde_json = "1.0"
rocket = "0.5.0-rc.1"

[dependencies.rocket_contrib]
version = "0.4"
default-features = false
features = ["json"]
  • 1
    Does this answer your question? [How to return JSON as a response in Rust Rocket with auto field deserialising?](https://stackoverflow.com/questions/68682054/how-to-return-json-as-a-response-in-rust-rocket-with-auto-field-deserialising) – Elias Holzmann Aug 27 '21 at 16:12
  • 3
    You are using rocket v5, rocket_contrib is for rocket v4. – Ivan C Aug 27 '21 at 16:15

2 Answers2

3

Since now we are at rocket v5 (the rocket_contrib crate was valid only for rocket v4), and checking that Cargo.toml have these dependencies:

...

[dependencies]
rocket = { version = "0.5.0-rc.2", features = ["json"] }
serde = "1.0.152"

...

To use the Json struct apply the following trait to MyStruct struct:

use rocket::serde::{json::Json, Serialize};

#[derive(Serialize)]
pub struct MyStruct;

pub fn get_timestamps(pool: &State<Pool>) -> Json<MyStruct> {...}

Having pumped your MyStruct struct with the rocket methods, you should be able to work with rocket::serde::json::Json

Mattia Samiolo
  • 365
  • 2
  • 8
0

I recommend to instead of

use rocket_contrib::json::Json;;

use this

use rocket::serde::json::Json;
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Mar 06 '23 at 08:54
  • This isn't in the docs. https://docs.rs/rocket/latest/rocket/?search=serde – yosemeti Mar 14 '23 at 02:10