Trait Deserializer
trait Deserializer<'de>: Sized
A data format that can deserialize any data structure supported by Serde.
The role of this trait is to define the deserialization half of the Serde
data model, which is a way to categorize every Rust data type into one of
29 possible types. Each method of the Deserializer trait corresponds to one
of the types of the data model.
Implementations of Deserialize map themselves into this data model by
passing to the Deserializer a Visitor implementation that can receive
these various types.
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
The Deserializer trait supports two entry point styles which enables
different kinds of deserialization.
-
The
deserialize_anymethod. Self-describing data formats like JSON are able to look at the serialized data and tell what it represents. For example the JSON deserializer may see an opening curly brace ({) and know that it is seeing a map. If the data format supportsDeserializer::deserialize_any, it will drive the Visitor using whatever type it sees in the input. JSON uses this approach when deserializingserde_json::Valuewhich is an enum that can represent any JSON document. Without knowing what is in a JSON document, we can deserialize it toserde_json::Valueby going throughDeserializer::deserialize_any. -
The various
deserialize_*methods. Non-self-describing formats like Postcard need to be told what is in the input in order to deserialize it. Thedeserialize_*methods are hints to the deserializer for how to interpret the next piece of input. Non-self-describing formats are not able to deserialize something likeserde_json::Valuewhich relies onDeserializer::deserialize_any.
When implementing Deserialize, you should avoid relying on
Deserializer::deserialize_any unless you need to be told by the
Deserializer what type is in the input. Know that relying on
Deserializer::deserialize_any means your data type will be able to
deserialize from self-describing formats only, ruling out Postcard and many
others.
Lifetime
The 'de lifetime of this trait is the lifetime of data that may be
borrowed from the input when deserializing. See the page Understanding
deserializer lifetimes for a more detailed explanation of these lifetimes.
Example implementation
The example data format presented on the website contains example code for
a basic JSON Deserializer.
Associated Types
type Error: TraitBound { trait_: Path { path: "Error", id: Id(217), args: None }, generic_params: [], modifier: None }The error type that can be returned if some error occurs during deserialization.
Required Methods
fn deserialize_any<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Require the
Deserializerto figure out how to drive the visitor based on what data type is in the input.When implementing
Deserialize, you should avoid relying onDeserializer::deserialize_anyunless you need to be told by the Deserializer what type is in the input. Know that relying onDeserializer::deserialize_anymeans your data type will be able to deserialize from self-describing formats only, ruling out Postcard and many others.fn deserialize_bool<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting aboolvalue.fn deserialize_i8<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting ani8value.fn deserialize_i16<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting ani16value.fn deserialize_i32<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting ani32value.fn deserialize_i64<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting ani64value.fn deserialize_u8<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting au8value.fn deserialize_u16<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting au16value.fn deserialize_u32<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting au32value.fn deserialize_u64<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting au64value.fn deserialize_f32<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting af32value.fn deserialize_f64<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting af64value.fn deserialize_char<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting acharvalue.fn deserialize_str<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a string value and does not benefit from taking ownership of buffered data owned by theDeserializer.If the
Visitorwould benefit from taking ownership ofStringdata, indicate this to theDeserializerby usingdeserialize_stringinstead.fn deserialize_string<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a string value and would benefit from taking ownership of buffered data owned by theDeserializer.If the
Visitorwould not benefit from taking ownership ofStringdata, indicate that to theDeserializerby usingdeserialize_strinstead.fn deserialize_bytes<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a byte array and does not benefit from taking ownership of buffered data owned by theDeserializer.If the
Visitorwould benefit from taking ownership ofVec<u8>data, indicate this to theDeserializerby usingdeserialize_byte_bufinstead.fn deserialize_byte_buf<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a byte array and would benefit from taking ownership of buffered data owned by theDeserializer.If the
Visitorwould not benefit from taking ownership ofVec<u8>data, indicate that to theDeserializerby usingdeserialize_bytesinstead.fn deserialize_option<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting an optional value.This allows deserializers that encode an optional value as a nullable value to convert the null value into
Noneand a regular value intoSome(value).fn deserialize_unit<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a unit value.fn deserialize_unit_struct<V>(self: Self, name: &'static str, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a unit struct with a particular name.fn deserialize_newtype_struct<V>(self: Self, name: &'static str, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a newtype struct with a particular name.fn deserialize_seq<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a sequence of values.fn deserialize_tuple<V>(self: Self, len: usize, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a sequence of values and knows how many values there are without looking at the serialized data.fn deserialize_tuple_struct<V>(self: Self, name: &'static str, len: usize, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a tuple struct with a particular name and number of fields.fn deserialize_map<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a map of key-value pairs.fn deserialize_struct<V>(self: Self, name: &'static str, fields: &'static [&'static str], visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting a struct with a particular name and fields.fn deserialize_enum<V>(self: Self, name: &'static str, variants: &'static [&'static str], visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting an enum value with a particular name and possible variants.fn deserialize_identifier<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting the name of a struct field or the discriminant of an enum variant.fn deserialize_ignored_any<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype needs to deserialize a value whose type doesn't matter because it is ignored.Deserializers for non-self-describing formats may not support this mode.
Provided Methods
fn deserialize_i128<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting ani128value.The default behavior unconditionally returns an error.
fn deserialize_u128<V>(self: Self, visitor: V) -> Result<<V as >::Value, <Self as >::Error> where V: Visitor<'de>Hint that the
Deserializetype is expecting anu128value.The default behavior unconditionally returns an error.
fn is_human_readable(self: &Self) -> boolDetermine whether
Deserializeimplementations should expect to deserialize their 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::ops::Add; # use std::str::FromStr; # # struct Timestamp; # # impl Timestamp { # const EPOCH: Timestamp = Timestamp; # } # # impl FromStr for Timestamp { # type Err = String; # fn from_str(_: &str) -> Result<Self, Self::Err> { # unimplemented!() # } # } # # struct Duration; # # impl Duration { # fn seconds(_: u64) -> Self { unimplemented!() } # } # # impl Add<Duration> for Timestamp { # type Output = Timestamp; # fn add(self, _: Duration) -> Self::Output { # unimplemented!() # } # } # use serde::de::{self, Deserialize, Deserializer}; impl<'de> Deserialize<'de> for Timestamp { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { if deserializer.is_human_readable() { // Deserialize from a human-readable string like "2015-05-15T17:01:00Z". let s = String::deserialize(deserializer)?; Timestamp::from_str(&s).map_err(de::Error::custom) } else { // Deserialize from a compact binary representation, seconds since // the Unix epoch. let n = u64::deserialize(deserializer)?; Ok(Timestamp::EPOCH + Duration::seconds(n)) } } }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<'de, E> Deserializer for IsizeDeserializer<E>impl<'de, E> Deserializer for I128Deserializer<E>impl<'de, E> Deserializer for I64Deserializer<E>impl<'de, E> Deserializer for UnitDeserializer<E>impl<'de, E> Deserializer for StringDeserializer<E>impl<'de, E> Deserializer for I32Deserializer<E>impl<'de, E> Deserializer for I16Deserializer<E>impl<'de, E> Deserializer for I8Deserializer<E>impl<'de, A> Deserializer for MapAccessDeserializer<A>impl<'de, E> Deserializer for BoolDeserializer<E>impl<'de, I, T, E> Deserializer for SeqDeserializer<I, E>impl<'de, E> Deserializer for BorrowedStrDeserializer<'de, E>impl<'de, E> Deserializer for U32Deserializer<E>impl<'de, I, E> Deserializer for MapDeserializer<'de, I, E>impl<'de, E> Deserializer for CharDeserializer<E>impl<'de, A> Deserializer for EnumAccessDeserializer<A>impl<'de, A> Deserializer for SeqAccessDeserializer<A>impl<'de, E> Deserializer for F64Deserializer<E>impl<'de, E> Deserializer for F32Deserializer<E>impl<'de, 'a, E> Deserializer for BytesDeserializer<'a, E>impl<'de, 'a, E> Deserializer for CowStrDeserializer<'a, E>impl<'de, E> Deserializer for UsizeDeserializer<E>impl<'de, 'a, E> Deserializer for StrDeserializer<'a, E>impl<'de, E> Deserializer for U128Deserializer<E>impl<'de, E> Deserializer for U64Deserializer<E>impl<'de, E> Deserializer for BorrowedBytesDeserializer<'de, E>impl<'de, E> Deserializer for U16Deserializer<E>impl<'de, E> Deserializer for U8Deserializer<E>