6 releases

0.1.6 Apr 27, 2023
0.1.5 Apr 21, 2023

#882 in Encoding

Apache-2.0

15KB
322 lines

Serialize views of data

Dynamically select during serialization which fields will be included.

Example

use serde_view::View;
use serde_view::ViewFields;

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, View)]
pub struct MyStruct {
    id: String,
    #[serde(default)]
    name: String,
    #[serde(default)]
    tags: Vec<String>,
}

fn serialize(my: &MyStruct) -> Result<serde_json::Value, serde_json::Error> {
    serde_json::to_value(my.as_view().with_fields([
       <MyStruct as View>::Fields::Id,
       <MyStruct as View>::Fields::Name,
   ]).unwrap())
}

lib.rs:

Serialize a view of a structure

The idea of this crate is to serialize only a sub-set of fields of a struct, making the decision which fields during runtime.

Basic example

Assume you have a struct like:

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MyStruct {
    id: String,
    #[serde(default)]
    name: String,
    #[serde(default)]
    tags: Vec<String>,
}

Now, you want to make it possible to only serialize a sub-set of the data, making this decision during runtime. This can be done by adding the View derive to the struct, and wrapping the serializing with the View::view function, adding extra information to the view context:

use serde_view::View;
use serde_view::ViewFields;

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, View)]
pub struct MyStruct {
    id: String,
    #[serde(default)]
    name: String,
    #[serde(default)]
    tags: Vec<String>,
}

fn serialize(my: &MyStruct) -> Result<serde_json::Value, serde_json::Error> {
    serde_json::to_value(my.as_view().with_fields([
        <MyStruct as View>::Fields::Id,
        <MyStruct as View>::Fields::Name,
    ]).unwrap())
}

fn serialize_str_fields(my: &MyStruct) -> Result<serde_json::Value, serde_json::Error> {
    // as fields can be converted to strings, it is also possible to pass something like a
    // comma separated list
    serde_json::to_value(my.as_view().with_fields(
        <MyStruct as View>::Fields::from_str_split("id,name").unwrap()
    ).unwrap())
}

Dependencies

~1.1–1.8MB
~35K SLoC