What is the best practice of using Json<T>
to parse req.body
#1921
-
I'm new to rocket, and trying to build a pastebin example based on a database. I want to use #[derive(Deserialize)]
pub struct ReqCode<'r> {
pub language: Option<&'r str>,
pub content: &'r str,
}
#[post("/", data = "<code>", format = "json")]
pub async fn create(
code: Json<ReqCode<'_>>,
db: &State<Arc<Rbatis>>,
) -> Result<Json<Uuid>, status::Forbidden<Json<RbatisError>>> {
let id = Uuid::new_v5(&Uuid::NAMESPACE_OID, code.content.as_bytes());
match db
.save(
&Code {
id,
language: code.language.map(String::from),
content: String::from(code.content),
created_at: NaiveDateTime::now(),
},
&[],
)
.await
{
Ok(_) => Ok(Json(id)),
Err(e) => Err(status::Forbidden(Some(Json(e)))),
}
} And I came across this error when trying a basic test: POST 127.0.0.1:8000 http/1.1
Content-Type: application/json
{
"language": "C",
"content": "printf(\"Hello World\n\");"
}
I tried to find the use rocket::serde::{Deserialize, json::Json};
#[derive(Deserialize)]
struct Task<'r> {
description: &'r str,
complete: bool
}
#[post("/todo", data = "<task>")]
fn new(task: Json<Task<'_>>) { /* .. */ } I tried this and it works: #[derive(Deserialize)]
pub struct ReqCode<'r> {
pub language: Option<&'r str>,
pub content: String,
} I wonder what is the best practice of using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is a current limitation of serde's zero-copy deserialization: if the input contains escape sequences, there is nowhere for
It hasn't been deleted entirely, but moved to https://github.com/SergioBenitez/Rocket/blob/v0.5-rc/examples/serialization/src/json.rs . (I think there are still a few broken links floating around that are fixed in the repository but not yet published). That example uses |
Beta Was this translation helpful? Give feedback.
This is a current limitation of serde's zero-copy deserialization: if the input contains escape sequences, there is nowhere for
serde
to put the decoded string such that an&'r str
could refer to it. ACow<'r, str>
orString
should work; see also serde-rs/json#742.It hasn't been deleted entirely, but moved to https://github.com/SergioBenitez/Rocket/blob/v0.5-rc/examples/serialization/src/json.rs . (I think there are still a few broken links floating around that are fixed in the repository but not yet published). That example uses
Cow<'r, str>
, which ought to work for you as well.