pub trait SerializePartial: Serialize {
    type Fields;
    type Filter: SerializeFilter<Self>;

    fn with_fields<F, I>(&self, select: F) -> Partial<'_, Self>
    where
        F: FnOnce(Self::Fields) -> I,
        I: IntoIterator<Item = Field<Self>>
; fn without_fields<F, I>(
        &self,
        select: F
    ) -> Partial<'_, Self, InverseFilter<Self>>
    where
        F: FnOnce(Self::Fields) -> I,
        I: IntoIterator<Item = Field<Self>>
, { ... } }
Expand description

Trait implemented by types which can be partially serialized.

Required Associated Types§

Type which provides the list of serializable fields.

When using the derive macro, this type is a struct with the same fields as the original struct. It will implement IntoIterator to make it possible to iterate over the available fields, and Copy and Clone for convenience. It will also have a FIELDS: Self associated constant.

Type which can be used to check whether a serializable field should be skipped.

Required Methods§

Returns a value which forwards the Serialize implementation but only serializes the selected fields.

The select closure receives an instance of Fields which can than be used to select which fields should be serialized. The closure can return any type which implements IntoIterator. This could be an array, but could also be a Vec or an Iterator with fields selected at runtime.

Example
use serde::Serialize;
use serde_partial::SerializePartial;

#[derive(Serialize, SerializePartial)]
#[serde(rename_all = "camelCase")]
struct User {
    full_name: &'static str,
    age: u8,
    #[serde(rename = "contact")]
    email: &'static str,
}

const USER: User = User {
    full_name: "John Doe",
    age: 42,
    email: "john.doe@example.com",
};

// serialize only the `full_name` field
let filtered = USER.with_fields(|u| [u.full_name]);
let json = serde_json::to_value(&filtered).unwrap();
assert_eq!(
    json,
    serde_json::json!({
        "fullName": USER.full_name,
    })
);

// the field list doesn't have to be an array
// serialize every field with a name longer than 4 characters
let filtered = USER.with_fields(|u| u.into_iter().filter(|f| f.name().len() > 4));
let json = serde_json::to_value(&filtered).unwrap();
assert_eq!(
    json,
    serde_json::json!({
        "fullName": USER.full_name,
        "contact": USER.email,
    })
);

// field names respect serde attributes
assert_eq!(<User as SerializePartial>::Fields::FIELDS.full_name.name(), "fullName");
assert_eq!(<User as SerializePartial>::Fields::FIELDS.age.name(), "age");
assert_eq!(<User as SerializePartial>::Fields::FIELDS.email.name(), "contact");

Provided Methods§

Same as with_fields but fields are opt-out instead of opt-in.

Example
let filtered = USER.without_fields(|u| [u.email]);
let json = serde_json::to_value(&filtered).unwrap();
assert_eq!(
    json,
    serde_json::json!({
        "fullName": USER.full_name,
        "age": USER.age,
    })
);

Implementors§