Macro rocket_contrib::json [−][src]
macro_rules! json { ($($json:tt)+) => { ... }; }
Expand description
A macro to create ad-hoc JSON serializable values using JSON syntax.
Usage
To import the macro, add the #[macro_use]
attribute to the extern crate rocket_contrib
invocation:
#[macro_use] extern crate rocket_contrib;
The return type of a json!
invocation is
JsonValue
. A value created with this macro can
be returned from a handler as follows:
use rocket_contrib::json::JsonValue; #[get("/json")] fn get_json() -> JsonValue { json!({ "key": "value", "array": [1, 2, 3, 4] }) }
The Responder
implementation for
JsonValue
serializes the value into a JSON string and sets it as the body
of the response with a Content-Type
of application/json
.
Examples
Create a simple JSON object with two keys: "username"
and "id"
:
let value = json!({ "username": "mjordan", "id": 23 });
Create a more complex object with a nested object and array:
let value = json!({ "code": 200, "success": true, "payload": { "features": ["serde", "json"], "ids": [12, 121], }, });
Variables or expressions can be interpolated into the JSON literal. Any type
interpolated into an array element or object value must implement serde’s
Serialize
trait, while any type interpolated into a object key must
implement Into<String>
.
let code = 200; let features = vec!["serde", "json"]; let value = json!({ "code": code, "success": code == 200, "payload": { features[0]: features[1] } });
Trailing commas are allowed inside both arrays and objects.
let value = json!([ "notice", "the", "trailing", "comma -->", ]);