Struct aitch::Json[][src]

pub struct Json<T>(pub T);

A wrapper, indicating a type should be automatically (de)serialized from/to a HTTP request/response body.

This feature requires a dependency on serde. This dependency is enabled by default, but can be disabled by removing the optional serde feature on the aitch crate.

To use a type with this wrapper, it must implement both serde::de::DeserializeOwned and serde::Serialize. This is because Json<T> can be used in both request/response bodies, and because chains of handlers may choose to serialize/deserialize the type back into a stream of bytes in order to process the requests. (See the Body trait for more information).

Examples

The following example accepts a request with a JSON payload, and uses this to construct a JSON response:

extern crate aitch;
extern crate http;
extern crate serde;
#[macro_use] extern crate serde_derive;

use aitch::servers::hyper::Server;
use aitch::{middlewares, Json, Responder, ResponseBuilder, Result};
use http::Request;

#[derive(Serialize, Deserialize)]
struct ReqParameters {
    message: String,
}

#[derive(Serialize, Deserialize)]
struct RespBody {
    message: String,
}

fn handler(req: Request<Json<ReqParameters>>, mut resp: ResponseBuilder) -> impl Responder {
    let req_params = req.into_body().json();
    let message = format!("You sent '{}'", req_params.message);
    let body = RespBody { message };

    resp.header(http::header::CONTENT_TYPE, "application/json")
        .body(Json(body))
}

Methods

impl<T> Json<T>
[src]

Unwraps the JSON wrapper, returning the underlying type.

Trait Implementations

impl<T> Body for Json<T> where
    T: DeserializeOwned + Serialize + Send + 'static, 
[src]

Consume a [BodyStream] and return a future which resolves to Self. Read more

Consume Self and returns a [BodyStream]. Read more

Convenience function to convert from one type implementing Body to another.

Auto Trait Implementations

impl<T> Send for Json<T> where
    T: Send

impl<T> Sync for Json<T> where
    T: Sync