pub trait DisplayJson {
// Required method
fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> Result;
}Expand description
A variant of the Display trait for JSON.
This trait allows Rust types to be formatted as valid JSON.
Unlike the standard Display trait, DisplayJson is designed for
JSON serialization and supports proper escaping,
indentation, and other JSON-specific formatting features.
§Implementation Notes
nojson provides built-in implementations for many common Rust types:
- Basic types (booleans, integers, floats, strings)
- Collection types (arrays, vectors, sets, maps)
- Nullable types (via
Option<T>) - Reference types
§Examples
Implementing DisplayJson for a struct:
use nojson::{DisplayJson, JsonFormatter, Json};
struct Person {
name: String,
age: u32,
email: Option<String>,
}
impl DisplayJson for Person {
fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
f.object(|f| {
f.member("name", &self.name)?;
f.member("age", &self.age)?;
f.member("email", &self.email)
})
}
}
// Now you can use it with `Json` wrapper
let person = Person {
name: "Alice".to_string(),
age: 30,
email: Some("alice@example.com".to_string()),
};
assert_eq!(
Json(&person).to_string(),
r#"{"name":"Alice","age":30,"email":"alice@example.com"}"#
);Generating JSON in-place using json():
use nojson::{DisplayJson, json};
use std::collections::BTreeMap;
// Build a JSON object with pretty-printing.
let object = json(|f| {
f.set_indent_size(2);
f.set_spacing(true);
f.object(|f| {
f.member("name", "Example")?;
f.member("counts", &[1, 2, 3])?;
f.member("config", json(|f| f.object(|f| {
f.member("enabled", true);
f.member("visible", false)
})))
})
});
// Generate a JSON text from the object.
let text = format!("\n{}", object);
assert_eq!(text, r#"
{
"name": "Example",
"counts": [
1,
2,
3
],
"config": {
"enabled": true,
"visible": false
}
}"#);Required Methods§
Sourcefn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> Result
fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> Result
Formats the value as JSON into the provided formatter.
This method is similar to Display::fmt(), but accepts a
JsonFormatter which provides additional methods for JSON-specific formatting.