3

I am trying to build a POST handler, that receives JSON data with rocket (version: 0.5.0-rc.1).

This is the code I wrote:

use rocket::{post, response::content, routes, serde::{Deserialize, Serialize}};

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(crate = "rocket::serde")]
#[serde(rename_all = "camelCase")]
pub struct MyData {
    a_field: String,
}

#[post("/route", format = "json", data = "<data>")]
fn post_my_data(data: content::Json<MyData>) -> std::io::Result<()> { 

    Ok(())
}

#[rocket::launch]
fn rocket() -> _ {
    rocket::build()
    .mount("/", routes![forster_order])
}

However I am unable to compile this:

error[E0277]: the trait bound `rocket::response::content::Json<Order>: FromData<'_>` is not satisfied
   --> src\main.rs:17:25
    |
17  | fn post_my_data(data: content::Json<MyData>) -> std::io::Result<()> {
    |                         ^^^^^^^ the trait `FromData<'_>` is not implemented for `rocket::response::content::Json<Order>`
    | 
   ::: C:\Users\me\.cargo\registry\src\github.com-1ecc6299db9ec823\rocket-0.5.0-rc.1\src\data\from_data.rs:194:41
    |
194 |     async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self>;
    |                                         -- required by this bound in `rocket::data::FromData::from_data`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

In the example I have seen that a lifetime identifier was used on the struct, that is deserialized, but none of the types I use require lifetime identifiers, so I can't assign an identifier to my struct.

Ho can I deserialize with a struct, that does not have a lifetime identifier?

frankenapps
  • 5,800
  • 6
  • 28
  • 69

1 Answers1

4

Your problem is not about lifetimes, you are using the wrong Json struct. You are using rocket::response::content::Json, this can be used to set the Content-Type of a response (see for example this). You want to use rocket::serde::json::Json:

//...
fn post_my_data(data: rocket::serde::json::Json<MyData>) -> std::io::Result<()> {
//...

Note that you must enable the Rocket feature json for this to be available.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
Elias Holzmann
  • 3,216
  • 2
  • 17
  • 33