Function rocket::serde::json::to_string

source ·
pub fn to_string<T>(value: &T) -> Result<String, Error>
where T: Serialize,
Available on crate feature json only.
Expand description

Serialize a T into a JSON string with compact representation.

Always use Json to serialize JSON response data.


use rocket::serde::{Deserialize, Serialize, json};

#[derive(Debug, PartialEq, Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
struct Data<'r> {
    framework: &'r str,
    stars: usize,

let data = Data {
    framework: "Rocket",
    stars: 5,

let string = json::to_string(&data).unwrap();
let data: Data = json::from_str(&string).unwrap();
assert_eq!(data, Data { framework: "Rocket", stars: 5, });


Serialization fails if T’s Serialize implementation fails or if T contains a map with non-string keys.