Skip to main content

SerializesToArray

Trait SerializesToArray 

Source
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§

Source

fn hidden() -> Vec<&'static str>
where Self: Sized,

Fields to exclude from serialization output (like $hidden).

Source

fn appends() -> Vec<&'static str>
where Self: Sized,

Computed attributes to append to serialization output (like $appends).

Source

fn get_appended(&self, _key: &str) -> Option<Value>

Return the value for a computed attribute.

Only called for keys returned by appends().

Source

fn to_array(&self) -> Value
where Self: Sized,

Convert the model to a JSON Value, respecting hidden / appends.

Source

fn to_json(&self) -> Result<String, Error>
where Self: Sized,

Convert the model to a pretty-printed JSON string.

Source

fn to_json_compact(&self) -> Result<String, Error>
where Self: Sized,

Convert the model to a compact JSON string.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§