Skip to main content
JSON extractor and response type. When used as an extractor, it deserializes request bodies into types that implement serde::DeserializeOwned. When used as a response, it serializes types that implement serde::Serialize to JSON.

Type signature

As an extractor

The Json extractor consumes the request body and deserializes it as JSON.
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.

Basic usage

Content-Type validation

The request must have a Content-Type: application/json header (or similar like application/problem+json). Requests without this header will be rejected with 415 Unsupported Media Type.

As a response

When returned from a handler, Json serializes the value to JSON and sets the Content-Type: application/json header automatically.

Error handling

Extractor rejections

415
The request doesn’t have a Content-Type: application/json header.
400
The body doesn’t contain syntactically valid JSON.
422
The body contains syntactically valid JSON, but it couldn’t be deserialized into the target type.
varies
Buffering the request body failed.

Example error responses

Response serialization errors

If serialization fails when using Json as a response, a 500 Internal Server Error will be returned with the error message as the body.

Parsing from bytes

You can construct a Json<T> from bytes directly:

Optional JSON

Use Option<Json<T>> to make JSON extraction optional based on the presence of a Content-Type header: