pub struct JsonDeserializer<T> { /* private fields */ }
json-deserializer
only.Expand description
JSON Extractor for zero-copy deserialization.
Deserialize request bodies into some type that implements serde::Deserialize<'de>
.
Parsing JSON is delayed until deserialize
is called.
If the type implements serde::de::DeserializeOwned
, the Json
extractor should
be preferred.
The request will be rejected (and a JsonDeserializerRejection
will be returned) if:
- The request doesn’t have a
Content-Type: application/json
(or similar) header. - Buffering the request body fails.
Additionally, a JsonRejection
error will be returned, when calling deserialize
if:
- The body doesn’t contain syntactically valid JSON.
- The body contains syntactically valid JSON, but it couldn’t be deserialized into the target type.
- Attempting to deserialize escaped JSON into a type that must be borrowed (e.g.
&'a str
).
⚠️ serde
will implicitly try to borrow for &str
and &[u8]
types, but will error if the
input contains escaped characters. Use Cow<'a, str>
or Cow<'a, [u8]>
, with the
#[serde(borrow)]
attribute, to allow serde to fall back to an owned type when encountering
escaped characters.
⚠️ Since parsing JSON requires consuming the request body, the Json
extractor must be
last if there are multiple extractors in a handler.
See “the order of extractors”
See JsonDeserializerRejection
for more details.
§Example
use axum::{
routing::post,
Router,
response::{IntoResponse, Response}
};
use axum_extra::extract::JsonDeserializer;
use serde::Deserialize;
use std::borrow::Cow;
use http::StatusCode;
#[derive(Deserialize)]
struct Data<'a> {
#[serde(borrow)]
borrow_text: Cow<'a, str>,
#[serde(borrow)]
borrow_bytes: Cow<'a, [u8]>,
borrow_dangerous: &'a str,
not_borrowed: String,
}
async fn upload(deserializer: JsonDeserializer<Data<'_>>) -> Response {
let data = match deserializer.deserialize() {
Ok(data) => data,
Err(e) => return e.into_response(),
};
// payload is a `Data` with borrowed data from `deserializer`,
// which owns the request body (`Bytes`).
StatusCode::OK.into_response()
}
let app = Router::new().route("/upload", post(upload));
Implementations§
Source§impl<'de, 'a: 'de, T> JsonDeserializer<T>where
T: Deserialize<'de>,
impl<'de, 'a: 'de, T> JsonDeserializer<T>where
T: Deserialize<'de>,
Sourcepub fn deserialize(&'a self) -> Result<T, JsonDeserializerRejection>
pub fn deserialize(&'a self) -> Result<T, JsonDeserializerRejection>
Deserialize the request body into the target type.
See JsonDeserializer
for more details.
Trait Implementations§
Source§impl<T: Clone> Clone for JsonDeserializer<T>
impl<T: Clone> Clone for JsonDeserializer<T>
Source§fn clone(&self) -> JsonDeserializer<T>
fn clone(&self) -> JsonDeserializer<T>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more