pub struct Json<T>(pub T);
Expand description
The JSON type: implements FromData
and Responder
, allowing you to
easily consume and respond with JSON.
§Receiving JSON
If you’re receiving JSON data, simply add a data
parameter to your route
arguments and ensure the type of the parameter is a Json<T>
, where T
is
some type you’d like to parse from JSON. T
must implement Deserialize
or from serde
. The data is parsed from the HTTP request body.
use rocket_contrib::json::Json;
#[post("/users", format = "json", data = "<user>")]
fn new_user(user: Json<User>) {
/* ... */
}
You don’t need to use format = "json"
, but it may be what you want.
Using format = json
means that any request that doesn’t specify
“application/json” as its Content-Type
header value will not be routed to
the handler.
§Sending JSON
If you’re responding with JSON data, return a Json<T>
type, where T
implements Serialize
from serde
. The content type of the response is
set to application/json
automatically.
use rocket_contrib::json::Json;
#[get("/users/<id>")]
fn user(id: usize) -> Json<User> {
let user_from_id = User::from(id);
/* ... */
Json(user_from_id)
}
§Incoming Data Limits
The default size limit for incoming JSON data is 1MiB. Setting a limit
protects your application from denial of service (DoS) attacks and from
resource exhaustion through high memory consumption. The limit can be
increased by setting the limits.json
configuration parameter. For
instance, to increase the JSON limit to 5MiB for all environments, you may
add the following to your Rocket.toml
:
[global.limits]
json = 5242880
Tuple Fields§
§0: T
Implementations§
Trait Implementations§
Source§impl<'a, T: Deserialize<'a>> FromData<'a> for Json<T>
impl<'a, T: Deserialize<'a>> FromData<'a> for Json<T>
Auto Trait Implementations§
impl<T> Freeze for Json<T>where
T: Freeze,
impl<T> RefUnwindSafe for Json<T>where
T: RefUnwindSafe,
impl<T> Send for Json<T>where
T: Send,
impl<T> Sync for Json<T>where
T: Sync,
impl<T> Unpin for Json<T>where
T: Unpin,
impl<T> UnwindSafe for Json<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
Source§impl<T> IntoSql for T
impl<T> IntoSql for T
Source§fn into_sql<T>(self) -> Self::Expressionwhere
Self: Sized + AsExpression<T>,
fn into_sql<T>(self) -> Self::Expressionwhere
Self: Sized + AsExpression<T>,
self
to an expression for Diesel’s query builder. Read moreSource§fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expressionwhere
&'a Self: AsExpression<T>,
fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expressionwhere
&'a Self: AsExpression<T>,
&self
to an expression for Diesel’s query builder. Read more