pub trait ToJsonNode {
// Required method
fn to_json_node(&self) -> JsonNode;
}
Expand description
A trait for converting a type into a JsonNode
.
Required Methods§
Sourcefn to_json_node(&self) -> JsonNode
fn to_json_node(&self) -> JsonNode
Converts the type into a JsonNode
.
§Implementing the Trait
use json_node::{JsonNode, JsonPropertyMap, ToJsonNode};
// Define some struct you want to convert into a `JsonNode`.
struct Person {
name: String,
age: i64,
}
// Implement the trait for your struct.
impl ToJsonNode for Person {
fn to_json_node(&self) -> JsonNode {
// Create a `JsonNode::Object` with the properties of your struct.
JsonNode::Object(JsonPropertyMap::from([
// The key is the name of the property. The value is the value of the property.
("name".to_owned(), JsonNode::String(self.name.clone())),
// You can convert any type that implements `ToJsonNode` into a `JsonNode`.
("age".to_owned(), self.age.to_json_node()),
]))
}
}
let person = Person {
name: "John Doe".to_owned(),
age: 42,
};
let person_node = person.to_json_node();
let person_node_json = person_node.to_json_string();
assert_eq!(
person_node_json,
r#"{"name":"John Doe","age":42}"#
);