pub struct Json<T>(pub T);
Json helper
Json can be used for two different purpose. First is for json response
generation and second is for extracting typed information from request's
payload.
To extract typed information from request's body, the type T
must
implement the Deserialize
trait from serde.
JsonConfig allows to configure extraction
process.
#[macro_use] extern crate serde_derive;
use actix_web::{App, Json, Result, http};
#[derive(Deserialize)]
struct Info {
username: String,
}
fn index(info: Json<Info>) -> Result<String> {
Ok(format!("Welcome {}!", info.username))
}
fn main() {
let app = App::new().resource(
"/index.html",
|r| r.method(http::Method::POST).with(index));
}
The Json
type allows you to respond with well-formed JSON data: simply
return a value of type Json where T is the type of a structure
to serialize into JSON. The type T
must implement the Serialize
trait from serde.
#[derive(Serialize)]
struct MyObj {
name: String,
}
fn index(req: HttpRequest) -> Result<Json<MyObj>> {
Ok(Json(MyObj {
name: req.match_info().query("name")?,
}))
}
Deconstruct to an inner value
The resulting type after dereferencing.
[+]
[−]
Mutably dereferences the value.
[+]
[+]
[+]
type Item = HttpResponse
The associated item which can be returned.
type Error = Error
The associated error which can be returned.
[−]
Convert itself to AsyncResult
or Error
.
[+]