Struct actix_web::Json

source ·
pub struct Json<T>(pub T);
Expand description

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.

Example

#[macro_use] extern crate serde_derive;
use actix_web::{App, Json, Result, http};

#[derive(Deserialize)]
struct Info {
    username: String,
}

/// deserialize `Info` from request's body
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));  // <- use `with` extractor
}

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")?,
    }))
}

Tuple Fields

0: T

Implementations

Deconstruct to an inner value

Trait Implementations

Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Mutably dereferences the value.
Formats the value using the given formatter. Read more
Configuration for conversion process
Future that resolves to a Self
Convert request to a Self
Convert request to a Self Read more
The associated item which can be returned.
The associated error which can be returned.
Convert itself to AsyncResult or Error.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.