pub trait SerializesToArray:
Send
+ Sync
+ Serialize {
// Provided methods
fn hidden() -> Vec<&'static str>
where Self: Sized { ... }
fn appends() -> Vec<&'static str>
where Self: Sized { ... }
fn get_appended(&self, _key: &str) -> Option<Value> { ... }
fn to_array(&self) -> Value
where Self: Sized { ... }
fn to_json(&self) -> Result<String, Error>
where Self: Sized { ... }
fn to_json_compact(&self) -> Result<String, Error>
where Self: Sized { ... }
}Expand description
Trait for model serialization — Laravel’s toArray() / toJson() pattern.
Models that implement this trait get automatic conversion to JSON with support for:
hidden()— fields to exclude from output (like$hidden)appends()— computed attributes to include (like$appends)get_appended()— compute values for appended attributes
§Example
ⓘ
impl SerializesToArray for User {
fn hidden() -> Vec<&'static str> { vec!["password"] }
fn appends() -> Vec<&'static str> { vec!["full_name"] }
fn get_appended(&self, key: &str) -> Option<Value> {
match key {
"full_name" => Some(json!(format!("{} {}", self.first_name, self.last_name))),
_ => None,
}
}
}Provided Methods§
Fields to exclude from serialization output (like $hidden).
Sourcefn appends() -> Vec<&'static str>where
Self: Sized,
fn appends() -> Vec<&'static str>where
Self: Sized,
Computed attributes to append to serialization output (like $appends).
Sourcefn get_appended(&self, _key: &str) -> Option<Value>
fn get_appended(&self, _key: &str) -> Option<Value>
Return the value for a computed attribute.
Only called for keys returned by appends().
Sourcefn to_array(&self) -> Valuewhere
Self: Sized,
fn to_array(&self) -> Valuewhere
Self: Sized,
Convert the model to a JSON Value, respecting hidden / appends.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".