Macro serializers::serializer
source · macro_rules! serializer {
{
#[derive( $($derive_tokens:tt),* )]
pub(crate) struct $name:ident<$type:ty> { $($body:tt)* }
} => { ... };
{
pub(crate) struct $name:ident<$type:ty> { $($body:tt)* }
} => { ... };
{
#[derive( $($derive_tokens:tt),* )]
pub struct $name:ident<$type:ty> { $($body:tt)* }
} => { ... };
{
pub struct $name:ident<$type:ty> { $($body:tt)* }
} => { ... };
{
#[derive( $($derive_tokens:tt),* )]
struct $name:ident<$type:ty> { $($body:tt)* }
} => { ... };
{
struct $name:ident<$type:ty> { $($body:tt)* }
} => { ... };
}
Expand description
This macro is the primary way to make serializers. See the top level docs for an example.
It expands into a struct the implements Serializer
.
Customization
The macro also lets you set separate JSON keys and field names. That is done by adding an
additional first argument to attr
, has_one
, or has_many
which will be the key.
You can also write pub
in front of the name of your strcut to make it public. Additionally you can write pub(crate)
to make it public within your crate.
You can also add #[derive(...)]
above the struct definition.
Example:
#[macro_use]
extern crate serializers;
#[macro_use]
extern crate serde_json;
use serializers::*;
pub struct User {
id: u64,
country: Country,
friends: Vec<User>,
}
#[derive(Clone)]
pub struct Country {
id: u64,
}
serializer! {
#[derive(Debug)]
pub struct UserSerializer<User> {
attr(identifier, id)
has_one(homeland, country, CountrySerializer)
has_many(buddies, friends, UserSerializer)
}
}
serializer! {
#[derive(Debug)]
pub(crate) struct CountrySerializer<Country> {
attr(code, id)
}
}
fn main() {
let denmark = Country {
id: 1,
};
let bob = User {
id: 1,
country: denmark.clone(),
friends: vec![
User {
id: 2,
country: denmark.clone(),
friends: vec![],
}
],
};
let json: String = UserSerializer::serialize(&bob);
assert_eq!(
json,
json!({
"buddies": [
{
"buddies": [],
"homeland": { "code": 1 },
"identifier": 2
}
],
"homeland": { "code": 1 },
"identifier": 1
}).to_string(),
);
}