Trait Serializer
trait Serializer: Sized
A data format that can serialize any data structure supported by Serde.
The role of this trait is to define the serialization half of the Serde
data model, which is a way to categorize every Rust data structure into one
of 29 possible types. Each method of the Serializer trait corresponds to
one of the types of the data model.
Implementations of Serialize map themselves into this data model by
invoking exactly one of the Serializer methods.
The types that make up the Serde data model are:
- 14 primitive types
- bool
- i8, i16, i32, i64, i128
- u8, u16, u32, u64, u128
- f32, f64
- char
- string
- UTF-8 bytes with a length and no null terminator.
- When serializing, all strings are handled equally. When deserializing, there are three flavors of strings: transient, owned, and borrowed.
- byte array - [u8]
- Similar to strings, during deserialization byte arrays can be transient, owned, or borrowed.
- option
- Either none or some value.
- unit
- The type of
()in Rust. It represents an anonymous value containing no data.
- The type of
- unit_struct
- For example
struct UnitorPhantomData<T>. It represents a named value containing no data.
- For example
- unit_variant
- For example the
E::AandE::Binenum E { A, B }.
- For example the
- newtype_struct
- For example
struct Millimeters(u8).
- For example
- newtype_variant
- For example the
E::Ninenum E { N(u8) }.
- For example the
- seq
- A variably sized heterogeneous sequence of values, for example
Vec<T>orHashSet<T>. When serializing, the length may or may not be known before iterating through all the data. When deserializing, the length is determined by looking at the serialized data.
- A variably sized heterogeneous sequence of values, for example
- tuple
- A statically sized heterogeneous sequence of values for which the
length will be known at deserialization time without looking at the
serialized data, for example
(u8,)or(String, u64, Vec<T>)or[u64; 10].
- A statically sized heterogeneous sequence of values for which the
length will be known at deserialization time without looking at the
serialized data, for example
- tuple_struct
- A named tuple, for example
struct Rgb(u8, u8, u8).
- A named tuple, for example
- tuple_variant
- For example the
E::Tinenum E { T(u8, u8) }.
- For example the
- map
- A heterogeneous key-value pairing, for example
BTreeMap<K, V>.
- A heterogeneous key-value pairing, for example
- struct
- A heterogeneous key-value pairing in which the keys are strings and
will be known at deserialization time without looking at the
serialized data, for example
struct S { r: u8, g: u8, b: u8 }.
- A heterogeneous key-value pairing in which the keys are strings and
will be known at deserialization time without looking at the
serialized data, for example
- struct_variant
- For example the
E::Sinenum E { S { r: u8, g: u8, b: u8 } }.
- For example the
Many Serde serializers produce text or binary data as output, for example
JSON or Postcard. This is not a requirement of the Serializer trait, and
there are serializers that do not produce text or binary output. One example
is the serde_json::value::Serializer (distinct from the main serde_json
serializer) that produces a serde_json::Value data structure in memory as
output.
Example implementation
The example data format presented on the website contains example code for
a basic JSON Serializer.
Associated Types
type OkThe output type produced by this
Serializerduring successful serialization. Most serializers that produce text or binary output should setOk = ()and serialize into anio::Writeor buffer contained within theSerializerinstance. Serializers that build in-memory data structures may be simplified by usingOkto propagate the data structure around.type Error: TraitBound { trait_: Path { path: "Error", id: Id(220), args: None }, generic_params: [], modifier: None }The error type when some error occurs during serialization.
type SerializeSeq: TraitBound { trait_: Path { path: "SerializeSeq", id: Id(2652), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Ok", args: None, binding: Equality(Type(QualifiedPath { name: "Ok", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }, AssocItemConstraint { name: "Error", args: None, binding: Equality(Type(QualifiedPath { name: "Error", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }] }) }, generic_params: [], modifier: None }Type returned from
serialize_seqfor serializing the content of the sequence.type SerializeTuple: TraitBound { trait_: Path { path: "SerializeTuple", id: Id(2653), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Ok", args: None, binding: Equality(Type(QualifiedPath { name: "Ok", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }, AssocItemConstraint { name: "Error", args: None, binding: Equality(Type(QualifiedPath { name: "Error", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }] }) }, generic_params: [], modifier: None }Type returned from
serialize_tuplefor serializing the content of the tuple.type SerializeTupleStruct: TraitBound { trait_: Path { path: "SerializeTupleStruct", id: Id(2654), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Ok", args: None, binding: Equality(Type(QualifiedPath { name: "Ok", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }, AssocItemConstraint { name: "Error", args: None, binding: Equality(Type(QualifiedPath { name: "Error", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }] }) }, generic_params: [], modifier: None }Type returned from
serialize_tuple_structfor serializing the content of the tuple struct.type SerializeTupleVariant: TraitBound { trait_: Path { path: "SerializeTupleVariant", id: Id(2655), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Ok", args: None, binding: Equality(Type(QualifiedPath { name: "Ok", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }, AssocItemConstraint { name: "Error", args: None, binding: Equality(Type(QualifiedPath { name: "Error", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }] }) }, generic_params: [], modifier: None }Type returned from
serialize_tuple_variantfor serializing the content of the tuple variant.type SerializeMap: TraitBound { trait_: Path { path: "SerializeMap", id: Id(2656), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Ok", args: None, binding: Equality(Type(QualifiedPath { name: "Ok", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }, AssocItemConstraint { name: "Error", args: None, binding: Equality(Type(QualifiedPath { name: "Error", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }] }) }, generic_params: [], modifier: None }Type returned from
serialize_mapfor serializing the content of the map.type SerializeStruct: TraitBound { trait_: Path { path: "SerializeStruct", id: Id(2657), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Ok", args: None, binding: Equality(Type(QualifiedPath { name: "Ok", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }, AssocItemConstraint { name: "Error", args: None, binding: Equality(Type(QualifiedPath { name: "Error", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }] }) }, generic_params: [], modifier: None }Type returned from
serialize_structfor serializing the content of the struct.type SerializeStructVariant: TraitBound { trait_: Path { path: "SerializeStructVariant", id: Id(2658), args: Some(AngleBracketed { args: [], constraints: [AssocItemConstraint { name: "Ok", args: None, binding: Equality(Type(QualifiedPath { name: "Ok", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }, AssocItemConstraint { name: "Error", args: None, binding: Equality(Type(QualifiedPath { name: "Error", args: None, self_type: Generic("Self"), trait_: Some(Path { path: "", id: Id(2651), args: None }) })) }] }) }, generic_params: [], modifier: None }Type returned from
serialize_struct_variantfor serializing the content of the struct variant.
Required Methods
fn serialize_bool(self: Self, v: bool) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
boolvalue.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for bool { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_bool(*self) } }fn serialize_i8(self: Self, v: i8) -> Result<<Self as >::Ok, <Self as >::Error>Serialize an
i8value.If the format does not differentiate between
i8andi64, a reasonable implementation would be to cast the value toi64and forward toserialize_i64.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for i8 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_i8(*self) } }fn serialize_i16(self: Self, v: i16) -> Result<<Self as >::Ok, <Self as >::Error>Serialize an
i16value.If the format does not differentiate between
i16andi64, a reasonable implementation would be to cast the value toi64and forward toserialize_i64.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for i16 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_i16(*self) } }fn serialize_i32(self: Self, v: i32) -> Result<<Self as >::Ok, <Self as >::Error>Serialize an
i32value.If the format does not differentiate between
i32andi64, a reasonable implementation would be to cast the value toi64and forward toserialize_i64.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for i32 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_i32(*self) } }fn serialize_i64(self: Self, v: i64) -> Result<<Self as >::Ok, <Self as >::Error>Serialize an
i64value.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for i64 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_i64(*self) } }fn serialize_u8(self: Self, v: u8) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
u8value.If the format does not differentiate between
u8andu64, a reasonable implementation would be to cast the value tou64and forward toserialize_u64.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for u8 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u8(*self) } }fn serialize_u16(self: Self, v: u16) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
u16value.If the format does not differentiate between
u16andu64, a reasonable implementation would be to cast the value tou64and forward toserialize_u64.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for u16 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u16(*self) } }fn serialize_u32(self: Self, v: u32) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
u32value.If the format does not differentiate between
u32andu64, a reasonable implementation would be to cast the value tou64and forward toserialize_u64.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for u32 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u32(*self) } }fn serialize_u64(self: Self, v: u64) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
u64value.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for u64 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u64(*self) } }fn serialize_f32(self: Self, v: f32) -> Result<<Self as >::Ok, <Self as >::Error>Serialize an
f32value.If the format does not differentiate between
f32andf64, a reasonable implementation would be to cast the value tof64and forward toserialize_f64.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for f32 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_f32(*self) } }fn serialize_f64(self: Self, v: f64) -> Result<<Self as >::Ok, <Self as >::Error>Serialize an
f64value.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for f64 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_f64(*self) } }fn serialize_char(self: Self, v: char) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a character.
If the format does not support characters, it is reasonable to serialize it as a single element
stror au32.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for char { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_char(*self) } }fn serialize_str(self: Self, v: &str) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
&str.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for str { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(self) } }fn serialize_bytes(self: Self, v: &[u8]) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a chunk of raw byte data.
Enables serializers to serialize byte slices more compactly or more efficiently than other types of slices. If no efficient implementation is available, a reasonable implementation would be to forward to
serialize_seq. If forwarded, the implementation looks usually just like this:# use serde::ser::{Serializer, SerializeSeq}; # use serde_core::__private::doc::Error; # # struct MySerializer; # # impl Serializer for MySerializer { # type Ok = (); # type Error = Error; # fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> { let mut seq = self.serialize_seq(Some(v.len()))?; for b in v { seq.serialize_element(b)?; } seq.end() } # # serde_core::__serialize_unimplemented! { # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some # unit unit_struct unit_variant newtype_struct newtype_variant # seq tuple tuple_struct tuple_variant map struct struct_variant # } # }fn serialize_none(self: Self) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
Nonevalue.# use serde::{Serialize, Serializer}; # # enum Option<T> { # Some(T), # None, # } # # use self::Option::{Some, None}; # impl<T> Serialize for Option<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { Some(ref value) => serializer.serialize_some(value), None => serializer.serialize_none(), } } } # # fn main() {}fn serialize_some<T>(self: Self, value: &T) -> Result<<Self as >::Ok, <Self as >::Error> where T: ?Sized + SerializeSerialize a
Some(T)value.# use serde::{Serialize, Serializer}; # # enum Option<T> { # Some(T), # None, # } # # use self::Option::{Some, None}; # impl<T> Serialize for Option<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { Some(ref value) => serializer.serialize_some(value), None => serializer.serialize_none(), } } } # # fn main() {}fn serialize_unit(self: Self) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
()value.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for () { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_unit() } }fn serialize_unit_struct(self: Self, name: &'static str) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a unit struct like
struct UnitorPhantomData<T>.A reasonable implementation would be to forward to
serialize_unit.use serde::{Serialize, Serializer}; struct Nothing; impl Serialize for Nothing { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_unit_struct("Nothing") } }fn serialize_unit_variant(self: Self, name: &'static str, variant_index: u32, variant: &'static str) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a unit variant like
E::Ainenum E { A, B }.The
nameis the name of the enum, thevariant_indexis the index of this variant within the enum, and thevariantis the name of the variant.use serde::{Serialize, Serializer}; enum E { A, B, } impl Serialize for E { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { E::A => serializer.serialize_unit_variant("E", 0, "A"), E::B => serializer.serialize_unit_variant("E", 1, "B"), } } }fn serialize_newtype_struct<T>(self: Self, name: &'static str, value: &T) -> Result<<Self as >::Ok, <Self as >::Error> where T: ?Sized + SerializeSerialize a newtype struct like
struct Millimeters(u8).Serializers are encouraged to treat newtype structs as insignificant wrappers around the data they contain. A reasonable implementation would be to forward to
value.serialize(self).use serde::{Serialize, Serializer}; struct Millimeters(u8); impl Serialize for Millimeters { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_newtype_struct("Millimeters", &self.0) } }fn serialize_newtype_variant<T>(self: Self, name: &'static str, variant_index: u32, variant: &'static str, value: &T) -> Result<<Self as >::Ok, <Self as >::Error> where T: ?Sized + SerializeSerialize a newtype variant like
E::Ninenum E { N(u8) }.The
nameis the name of the enum, thevariant_indexis the index of this variant within the enum, and thevariantis the name of the variant. Thevalueis the data contained within this newtype variant.use serde::{Serialize, Serializer}; enum E { M(String), N(u8), } impl Serialize for E { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s), E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n), } } }fn serialize_seq(self: Self, len: Option<usize>) -> Result<<Self as >::SerializeSeq, <Self as >::Error>Begin to serialize a variably sized sequence. This call must be followed by zero or more calls to
serialize_element, then a call toend.The argument is the number of elements in the sequence, which may or may not be computable before the sequence is iterated. Some serializers only support sequences whose length is known up front.
# use std::marker::PhantomData; # # struct Vec<T>(PhantomData<T>); # # impl<T> Vec<T> { # fn len(&self) -> usize { # unimplemented!() # } # } # # impl<'a, T> IntoIterator for &'a Vec<T> { # type Item = &'a T; # type IntoIter = Box<dyn Iterator<Item = &'a T>>; # # fn into_iter(self) -> Self::IntoIter { # unimplemented!() # } # } # use serde::ser::{Serialize, SerializeSeq, Serializer}; impl<T> Serialize for Vec<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(Some(self.len()))?; for element in self { seq.serialize_element(element)?; } seq.end() } }fn serialize_tuple(self: Self, len: usize) -> Result<<Self as >::SerializeTuple, <Self as >::Error>Begin to serialize a statically sized sequence whose length will be known at deserialization time without looking at the serialized data. This call must be followed by zero or more calls to
serialize_element, then a call toend.use serde::ser::{Serialize, SerializeTuple, Serializer}; # mod fool { # trait Serialize {} impl<A, B, C> Serialize for (A, B, C) # {} # } # # struct Tuple3<A, B, C>(A, B, C); # # impl<A, B, C> Serialize for Tuple3<A, B, C> where A: Serialize, B: Serialize, C: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut tup = serializer.serialize_tuple(3)?; tup.serialize_element(&self.0)?; tup.serialize_element(&self.1)?; tup.serialize_element(&self.2)?; tup.end() } }use serde::ser::{Serialize, SerializeTuple, Serializer}; const VRAM_SIZE: usize = 386; struct Vram([u16; VRAM_SIZE]); impl Serialize for Vram { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_tuple(VRAM_SIZE)?; for element in &self.0[..] { seq.serialize_element(element)?; } seq.end() } }fn serialize_tuple_struct(self: Self, name: &'static str, len: usize) -> Result<<Self as >::SerializeTupleStruct, <Self as >::Error>Begin to serialize a tuple struct like
struct Rgb(u8, u8, u8). This call must be followed by zero or more calls toserialize_field, then a call toend.The
nameis the name of the tuple struct and thelenis the number of data fields that will be serialized.use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; struct Rgb(u8, u8, u8); impl Serialize for Rgb { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; ts.serialize_field(&self.0)?; ts.serialize_field(&self.1)?; ts.serialize_field(&self.2)?; ts.end() } }fn serialize_tuple_variant(self: Self, name: &'static str, variant_index: u32, variant: &'static str, len: usize) -> Result<<Self as >::SerializeTupleVariant, <Self as >::Error>Begin to serialize a tuple variant like
E::Tinenum E { T(u8, u8) }. This call must be followed by zero or more calls toserialize_field, then a call toend.The
nameis the name of the enum, thevariant_indexis the index of this variant within the enum, thevariantis the name of the variant, and thelenis the number of data fields that will be serialized.use serde::ser::{Serialize, SerializeTupleVariant, Serializer}; enum E { T(u8, u8), U(String, u32, u32), } impl Serialize for E { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { E::T(ref a, ref b) => { let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; tv.serialize_field(a)?; tv.serialize_field(b)?; tv.end() } E::U(ref a, ref b, ref c) => { let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; tv.serialize_field(a)?; tv.serialize_field(b)?; tv.serialize_field(c)?; tv.end() } } } }fn serialize_map(self: Self, len: Option<usize>) -> Result<<Self as >::SerializeMap, <Self as >::Error>Begin to serialize a map. This call must be followed by zero or more calls to
serialize_keyandserialize_value, then a call toend.The argument is the number of elements in the map, which may or may not be computable before the map is iterated. Some serializers only support maps whose length is known up front.
# use std::marker::PhantomData; # # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>); # # impl<K, V> HashMap<K, V> { # fn len(&self) -> usize { # unimplemented!() # } # } # # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { # type Item = (&'a K, &'a V); # type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>; # # fn into_iter(self) -> Self::IntoIter { # unimplemented!() # } # } # use serde::ser::{Serialize, SerializeMap, Serializer}; impl<K, V> Serialize for HashMap<K, V> where K: Serialize, V: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut map = serializer.serialize_map(Some(self.len()))?; for (k, v) in self { map.serialize_entry(k, v)?; } map.end() } }fn serialize_struct(self: Self, name: &'static str, len: usize) -> Result<<Self as >::SerializeStruct, <Self as >::Error>Begin to serialize a struct like
struct Rgb { r: u8, g: u8, b: u8 }. This call must be followed by zero or more calls toserialize_field, then a call toend.The
nameis the name of the struct and thelenis the number of data fields that will be serialized.lendoes not include fields which are skipped withSerializeStruct::skip_field.use serde::ser::{Serialize, SerializeStruct, Serializer}; struct Rgb { r: u8, g: u8, b: u8, } impl Serialize for Rgb { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut rgb = serializer.serialize_struct("Rgb", 3)?; rgb.serialize_field("r", &self.r)?; rgb.serialize_field("g", &self.g)?; rgb.serialize_field("b", &self.b)?; rgb.end() } }fn serialize_struct_variant(self: Self, name: &'static str, variant_index: u32, variant: &'static str, len: usize) -> Result<<Self as >::SerializeStructVariant, <Self as >::Error>Begin to serialize a struct variant like
E::Sinenum E { S { r: u8, g: u8, b: u8 } }. This call must be followed by zero or more calls toserialize_field, then a call toend.The
nameis the name of the enum, thevariant_indexis the index of this variant within the enum, thevariantis the name of the variant, and thelenis the number of data fields that will be serialized.lendoes not include fields which are skipped withSerializeStructVariant::skip_field.use serde::ser::{Serialize, SerializeStructVariant, Serializer}; enum E { S { r: u8, g: u8, b: u8 }, } impl Serialize for E { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { E::S { ref r, ref g, ref b, } => { let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; sv.serialize_field("r", r)?; sv.serialize_field("g", g)?; sv.serialize_field("b", b)?; sv.end() } } } }
Provided Methods
fn serialize_i128(self: Self, v: i128) -> Result<<Self as >::Ok, <Self as >::Error>Serialize an
i128value.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for i128 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_i128(*self) } }The default behavior unconditionally returns an error.
fn serialize_u128(self: Self, v: u128) -> Result<<Self as >::Ok, <Self as >::Error>Serialize a
u128value.# use serde::Serializer; # # serde_core::__private_serialize!(); # impl Serialize for u128 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u128(*self) } }The default behavior unconditionally returns an error.
fn collect_seq<I>(self: Self, iter: I) -> Result<<Self as >::Ok, <Self as >::Error> where I: IntoIterator, <I as IntoIterator>::Item: SerializeCollect an iterator as a sequence.
The default implementation serializes each item yielded by the iterator using
serialize_seq. Implementors should not need to override this method.use serde::{Serialize, Serializer}; struct SecretlyOneHigher { data: Vec<i32>, } impl Serialize for SecretlyOneHigher { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_seq(self.data.iter().map(|x| x + 1)) } }fn collect_map<K, V, I>(self: Self, iter: I) -> Result<<Self as >::Ok, <Self as >::Error> where K: Serialize, V: Serialize, I: IntoIterator<Item = (K, V)>Collect an iterator as a map.
The default implementation serializes each pair yielded by the iterator using
serialize_map. Implementors should not need to override this method.use serde::{Serialize, Serializer}; use std::collections::BTreeSet; struct MapToUnit { keys: BTreeSet<i32>, } // Serializes as a map in which the values are all unit. impl Serialize for MapToUnit { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_map(self.keys.iter().map(|k| (k, ()))) } }fn collect_str<T>(self: Self, value: &T) -> Result<<Self as >::Ok, <Self as >::Error> where T: ?Sized + DisplaySerialize a string produced by an implementation of
Display.The default implementation builds a heap-allocated
Stringand delegates toserialize_str. Serializers are encouraged to provide a more efficient implementation if possible.# struct DateTime; # # impl DateTime { # fn naive_local(&self) -> () { () } # fn offset(&self) -> () { () } # } # use serde::{Serialize, Serializer}; impl Serialize for DateTime { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset())) } }fn is_human_readable(self: &Self) -> boolDetermine whether
Serializeimplementations should serialize in human-readable form.Some types have a human-readable form that may be somewhat expensive to construct, as well as a binary form that is compact and efficient. Generally text-based formats like JSON and YAML will prefer to use the human-readable one and binary formats like Postcard will prefer the compact one.
# use std::fmt::{self, Display}; # # struct Timestamp; # # impl Timestamp { # fn seconds_since_epoch(&self) -> u64 { unimplemented!() } # } # # impl Display for Timestamp { # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { # unimplemented!() # } # } # use serde::{Serialize, Serializer}; impl Serialize for Timestamp { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if serializer.is_human_readable() { // Serialize to a human-readable string "2015-05-15T17:01:00Z". self.to_string().serialize(serializer) } else { // Serialize to a compact binary representation. self.seconds_since_epoch().serialize(serializer) } } }The default implementation of this method returns
true. Data formats may override this tofalseto request a compact form for types that support one. Note that modifying this method to change a format from human-readable to compact or vice versa should be regarded as a breaking change, as a value serialized in human-readable mode is not required to deserialize from the same data in compact mode.
Implementors
impl<'a> Serializer for &mut Formatter<'a>