//! Deserialize JSON data to a Rust data structure.
usecrate::error::{Error, ErrorCode, Result}; #[cfg(feature = "float_roundtrip")] usecrate::lexical; usecrate::number::Number; usecrate::read::{self, Fused, Reference}; use alloc::string::String; use alloc::vec::Vec; #[cfg(feature = "float_roundtrip")] use core::iter; use core::iter::FusedIterator; use core::marker::PhantomData; use core::result; use core::str::FromStr; use serde::de::{self, Expected, Unexpected}; use serde::forward_to_deserialize_any;
/// A structure that deserializes JSON into Rust values. pubstruct Deserializer<R> {
read: R,
scratch: Vec<u8>,
remaining_depth: u8, #[cfg(feature = "float_roundtrip")]
single_precision: bool, #[cfg(feature = "unbounded_depth")]
disable_recursion_limit: bool,
}
impl<'de, R> Deserializer<R> where
R: read::Read<'de>,
{ /// Create a JSON deserializer from one of the possible serde_json input /// sources. /// /// Typically it is more convenient to use one of these methods instead: /// /// - Deserializer::from_str /// - Deserializer::from_slice /// - Deserializer::from_reader pubfn new(read: R) -> Self {
Deserializer {
read,
scratch: Vec::new(),
remaining_depth: 128, #[cfg(feature = "float_roundtrip")]
single_precision: false, #[cfg(feature = "unbounded_depth")]
disable_recursion_limit: false,
}
}
}
#[cfg(feature = "std")] impl<R> Deserializer<read::IoRead<R>> where
R: crate::io::Read,
{ /// Creates a JSON deserializer from an `io::Read`. /// /// Reader-based deserializers do not support deserializing borrowed types /// like `&str`, since the `std::io::Read` trait has no non-copying methods /// -- everything it does involves copying bytes out of the data source. pubfn from_reader(reader: R) -> Self {
Deserializer::new(read::IoRead::new(reader))
}
}
impl<'a> Deserializer<read::SliceRead<'a>> { /// Creates a JSON deserializer from a `&[u8]`. pubfn from_slice(bytes: &'a [u8]) -> Self {
Deserializer::new(read::SliceRead::new(bytes))
}
}
impl<'a> Deserializer<read::StrRead<'a>> { /// Creates a JSON deserializer from a `&str`. pubfn from_str(s: &'a str) -> Self {
Deserializer::new(read::StrRead::new(s))
}
}
macro_rules! overflow {
($a:ident * 10 + $b:ident, $c:expr) => { match $c {
c => $a >= c / 10 && ($a > c / 10 || $b > c % 10),
}
};
}
impl<'de, R: Read<'de>> Deserializer<R> { /// The `Deserializer::end` method should be called after a value has been fully deserialized. /// This allows the `Deserializer` to validate that the input stream is at the end or that it /// only has trailing whitespace. pubfn end(&mutself) -> Result<()> { match tri!(self.parse_whitespace()) {
Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)),
None => Ok(()),
}
}
/// Turn a JSON deserializer into an iterator over values of type T. pubfn into_iter<T>(self) -> StreamDeserializer<'de, R, T> where
T: de::Deserialize<'de>,
{ // This cannot be an implementation of std::iter::IntoIterator because // we need the caller to choose what T is. let offset = self.read.byte_offset();
StreamDeserializer {
de: self,
offset,
failed: false,
output: PhantomData,
lifetime: PhantomData,
}
}
/// Parse arbitrarily deep JSON structures without any consideration for /// overflowing the stack. /// /// You will want to provide some other way to protect against stack /// overflows, such as by wrapping your Deserializer in the dynamically /// growing stack adapter provided by the serde_stacker crate. Additionally /// you will need to be careful around other recursive operations on the /// parsed result which may overflow the stack after deserialization has /// completed, including, but not limited to, Display and Debug and Drop /// impls. /// /// *This method is only available if serde_json is built with the /// `"unbounded_depth"` feature.* /// /// # Examples /// /// ``` /// use serde::Deserialize; /// use serde_json::Value; /// /// fn main() { /// let mut json = String::new(); /// for _ in 0..10000 { /// json = format!("[{}]", json); /// } /// /// let mut deserializer = serde_json::Deserializer::from_str(&json); /// deserializer.disable_recursion_limit(); /// let deserializer = serde_stacker::Deserializer::new(&mut deserializer); /// let value = Value::deserialize(deserializer).unwrap(); /// /// carefully_drop_nested_arrays(value); /// } /// /// fn carefully_drop_nested_arrays(value: Value) { /// let mut stack = vec![value]; /// while let Some(value) = stack.pop() { /// if let Value::Array(array) = value { /// stack.extend(array); /// } /// } /// } /// ``` #[cfg(feature = "unbounded_depth")] #[cfg_attr(docsrs, doc(cfg(feature = "unbounded_depth")))] pubfn disable_recursion_limit(&mutself) { self.disable_recursion_limit = true;
}
/// Error caused by a byte from next_char(). #[cold] fn error(&self, reason: ErrorCode) -> Error { let position = self.read.position();
Error::syntax(reason, position.line, position.column)
}
/// Error caused by a byte from peek(). #[cold] fn peek_error(&self, reason: ErrorCode) -> Error { let position = self.read.peek_position();
Error::syntax(reason, position.line, position.column)
}
/// Returns the first non-whitespace byte without consuming it, or `None` if /// EOF is encountered. fn parse_whitespace(&mutself) -> Result<Option<u8>> { loop { match tri!(self.peek()) {
Some(b' ' | b'\n' | b'\t' | b'\r') => { self.eat_char();
}
other => { return Ok(other);
}
}
}
}
fn parse_ident(&mutself, ident: &[u8]) -> Result<()> { for expected in ident { match tri!(self.next_char()) {
None => { return Err(self.error(ErrorCode::EofWhileParsingValue));
}
Some(next) => { if next != *expected { return Err(self.error(ErrorCode::ExpectedSomeIdent));
}
}
}
}
Ok(())
}
fn parse_integer(&mutself, positive: bool) -> Result<ParserNumber> { let next = match tri!(self.next_char()) {
Some(b) => b,
None => { return Err(self.error(ErrorCode::EofWhileParsingValue));
}
};
match next {
b'0' => { // There can be only one leading '0'. match tri!(self.peek_or_null()) {
b'0'..=b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)),
_ => self.parse_number(positive, 0),
}
}
c @ b'1'..=b'9' => { letmut significand = (c - b'0') as u64;
loop { match tri!(self.peek_or_null()) {
c @ b'0'..=b'9' => { let digit = (c - b'0') as u64;
// We need to be careful with overflow. If we can, // try to keep the number as a `u64` until we grow // too large. At that point, switch to parsing the // value as a `f64`. if overflow!(significand * 10 + digit, u64::MAX) { return Ok(ParserNumber::F64(tri!( self.parse_long_integer(positive, significand),
)));
}
// Error if there is not at least one digit after the decimal point. if exponent_after_decimal_point == 0 { match tri!(self.peek()) {
Some(_) => return Err(self.peek_error(ErrorCode::InvalidNumber)),
None => return Err(self.peek_error(ErrorCode::EofWhileParsingValue)),
}
}
let next = match tri!(self.next_char()) {
Some(b) => b,
None => { return Err(self.error(ErrorCode::EofWhileParsingValue));
}
};
// Make sure a digit follows the exponent place. letmut exp = match next {
c @ b'0'..=b'9' => (c - b'0') as i32,
_ => { return Err(self.error(ErrorCode::InvalidNumber));
}
};
whilelet c @ b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); let digit = (c - b'0') as i32;
if overflow!(exp * 10 + digit, i32::MAX) { let zero_significand = significand == 0; returnself.parse_exponent_overflow(positive, zero_significand, positive_exp);
}
exp = exp * 10 + digit;
}
let final_exp = if positive_exp {
starting_exp.saturating_add(exp)
} else {
starting_exp.saturating_sub(exp)
};
#[cfg(feature = "float_roundtrip")] fn f64_from_parts(&mutself, positive: bool, significand: u64, exponent: i32) -> Result<f64> { let f = ifself.single_precision {
lexical::parse_concise_float::<f32>(significand, exponent) as f64
} else {
lexical::parse_concise_float::<f64>(significand, exponent)
};
if f.is_infinite() {
Err(self.error(ErrorCode::NumberOutOfRange))
} else {
Ok(if positive { f } else { -f })
}
}
#[cfg(not(feature = "float_roundtrip"))] fn f64_from_parts(
&mutself,
positive: bool,
significand: u64, mut exponent: i32,
) -> Result<f64> { letmut f = significand as f64; loop { match POW10.get(exponent.wrapping_abs() as usize) {
Some(&pow) => { if exponent >= 0 {
f *= pow; if f.is_infinite() { return Err(self.error(ErrorCode::NumberOutOfRange));
}
} else {
f /= pow;
} break;
}
None => { if f == 0.0 { break;
} if exponent >= 0 { return Err(self.error(ErrorCode::NumberOutOfRange));
}
f /= 1e308;
exponent += 308;
}
}
}
Ok(if positive { f } else { -f })
}
#[cfg(feature = "float_roundtrip")] #[cold] #[inline(never)] fn parse_long_integer(&mutself, positive: bool, partial_significand: u64) -> Result<f64> { // To deserialize floats we'll first push the integer and fraction // parts, both as byte strings, into the scratch buffer and then feed // both slices to lexical's parser. For example if the input is // `12.34e5` we'll push b"1234" into scratch and then pass b"12" and // b"34" to lexical. `integer_end` will be used to track where to split // the scratch buffer. // // Note that lexical expects the integer part to contain *no* leading // zeroes and the fraction part to contain *no* trailing zeroes. The // first requirement is already handled by the integer parsing logic. // The second requirement will be enforced just before passing the // slices to lexical in f64_long_from_parts. self.scratch.clear(); self.scratch
.extend_from_slice(itoa::Buffer::new().format(partial_significand).as_bytes());
let next = match tri!(self.next_char()) {
Some(b) => b,
None => { return Err(self.error(ErrorCode::EofWhileParsingValue));
}
};
// Make sure a digit follows the exponent place. letmut exp = match next {
c @ b'0'..=b'9' => (c - b'0') as i32,
_ => { return Err(self.error(ErrorCode::InvalidNumber));
}
};
whilelet c @ b'0'..=b'9' = tri!(self.peek_or_null()) { self.eat_char(); let digit = (c - b'0') as i32;
if overflow!(exp * 10 + digit, i32::MAX) { let zero_significand = self.scratch.iter().all(|&digit| digit == b'0'); returnself.parse_exponent_overflow(positive, zero_significand, positive_exp);
}
exp = exp * 10 + digit;
}
let final_exp = if positive_exp { exp } else { -exp };
// This cold code should not be inlined into the middle of the hot // exponent-parsing loop above. #[cold] #[inline(never)] fn parse_exponent_overflow(
&mutself,
positive: bool,
zero_significand: bool,
positive_exp: bool,
) -> Result<f64> { // Error instead of +/- infinity. if !zero_significand && positive_exp { return Err(self.error(ErrorCode::NumberOutOfRange));
}
let value = match peek {
b'-' => { self.eat_char(); self.parse_any_number(false)
}
b'0'..=b'9' => self.parse_any_number(true),
_ => Err(self.peek_error(ErrorCode::InvalidNumber)),
};
let value = match tri!(self.peek()) {
Some(_) => Err(self.peek_error(ErrorCode::InvalidNumber)),
None => value,
};
match value {
Ok(value) => Ok(value), // The de::Error impl creates errors with unknown line and column. // Fill in the position here by looking at the current index in the // input. There is no way to tell whether this should call `error` // or `peek_error` so pick the one that seems correct more often. // Worst case, the position is off by one character.
Err(err) => Err(self.fix_position(err)),
}
}
match value {
Ok(value) => Ok(value), // The de::Error impl creates errors with unknown line and column. // Fill in the position here by looking at the current index in the // input. There is no way to tell whether this should call `error` // or `peek_error` so pick the one that seems correct more often. // Worst case, the position is off by one character.
Err(err) => Err(self.fix_position(err)),
}
}
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> where
V: de::Visitor<'de>,
{ let peek = match tri!(self.parse_whitespace()) {
Some(b) => b,
None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
};
let value = match peek {
b't' => { self.eat_char();
tri!(self.parse_ident(b"rue"));
visitor.visit_bool(true)
}
b'f' => { self.eat_char();
tri!(self.parse_ident(b"alse"));
visitor.visit_bool(false)
}
_ => Err(self.peek_invalid_type(&visitor)),
};
match value {
Ok(value) => Ok(value),
Err(err) => Err(self.fix_position(err)),
}
}
/// Parses a JSON string as bytes. Note that this function does not check /// whether the bytes represent a valid UTF-8 string. /// /// The relevant part of the JSON specification is Section 8.2 of [RFC /// 7159]: /// /// > When all the strings represented in a JSON text are composed entirely /// > of Unicode characters (however escaped), then that JSON text is /// > interoperable in the sense that all software implementations that /// > parse it will agree on the contents of names and of string values in /// > objects and arrays. /// > /// > However, the ABNF in this specification allows member names and string /// > values to contain bit sequences that cannot encode Unicode characters; /// > for example, "\uDEAD" (a single unpaired UTF-16 surrogate). Instances /// > of this have been observed, for example, when a library truncates a /// > UTF-16 string without checking whether the truncation split a /// > surrogate pair. The behavior of software that receives JSON texts /// > containing such values is unpredictable; for example, implementations /// > might return different values for the length of a string value or even /// > suffer fatal runtime exceptions. /// /// [RFC 7159]: https://tools.ietf.org/html/rfc7159 /// /// The behavior of serde_json is specified to fail on non-UTF-8 strings /// when deserializing into Rust UTF-8 string types such as String, and /// succeed with non-UTF-8 bytes when deserializing using this method. /// /// Escape sequences are processed as usual, and for `\uXXXX` escapes it is /// still checked if the hex number represents a valid Unicode code point. /// /// # Examples /// /// You can use this to parse JSON strings containing invalid UTF-8 bytes, /// or unpaired surrogates. /// /// ``` /// use serde_bytes::ByteBuf; /// /// fn look_at_bytes() -> Result<(), serde_json::Error> { /// let json_data = b"\"some bytes: \xe5\x00\xe5\""; /// let bytes: ByteBuf = serde_json::from_slice(json_data)?; /// /// assert_eq!(b'\xe5', bytes[12]); /// assert_eq!(b'\0', bytes[13]); /// assert_eq!(b'\xe5', bytes[14]); /// /// Ok(()) /// } /// # /// # look_at_bytes().unwrap(); /// ``` /// /// Backslash escape sequences like `\n` are still interpreted and required /// to be valid. `\u` escape sequences are required to represent a valid /// Unicode code point or lone surrogate. /// /// ``` /// use serde_bytes::ByteBuf; /// /// fn look_at_bytes() -> Result<(), serde_json::Error> { /// let json_data = b"\"lone surrogate: \\uD801\""; /// let bytes: ByteBuf = serde_json::from_slice(json_data)?; /// let expected = b"lone surrogate: \xED\xA0\x81"; /// assert_eq!(expected, bytes.as_slice()); /// Ok(()) /// } /// # /// # look_at_bytes(); /// ``` fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> where
V: de::Visitor<'de>,
{ let peek = match tri!(self.parse_whitespace()) {
Some(b) => b,
None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
};
let value = match peek {
b'"' => { self.eat_char(); self.scratch.clear(); match tri!(self.read.parse_str_raw(&mutself.scratch)) {
Reference::Borrowed(b) => visitor.visit_borrowed_bytes(b),
Reference::Copied(b) => visitor.visit_bytes(b),
}
}
b'[' => self.deserialize_seq(visitor),
_ => Err(self.peek_invalid_type(&visitor)),
};
match value {
Ok(value) => Ok(value),
Err(err) => Err(self.fix_position(err)),
}
}
/// Parses a `null` as a None, and any other values as a `Some(...)`. #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> where
V: de::Visitor<'de>,
{ match tri!(self.parse_whitespace()) {
Some(b'n') => { self.eat_char();
tri!(self.parse_ident(b"ull"));
visitor.visit_none()
}
_ => visitor.visit_some(self),
}
}
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> where
V: de::Visitor<'de>,
{ let peek = match tri!(self.parse_whitespace()) {
Some(b) => b,
None => { return Err(self.peek_error(ErrorCode::EofWhileParsingValue));
}
};
let value = match peek {
b'n' => { self.eat_char();
tri!(self.parse_ident(b"ull"));
visitor.visit_unit()
}
_ => Err(self.peek_invalid_type(&visitor)),
};
match value {
Ok(value) => Ok(value),
Err(err) => Err(self.fix_position(err)),
}
}
match value {
Ok(value) => Ok(value),
Err(err) => Err(self.fix_position(err)),
}
}
/// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight /// value, a `[..]`, or a `{..}`. #[inline] fn deserialize_enum<V>( self,
_name: &str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value> where
V: de::Visitor<'de>,
{ match tri!(self.parse_whitespace()) {
Some(b'{') => {
check_recursion! { self.eat_char(); let value = tri!(visitor.visit_enum(VariantAccess::new(self)));
}
/// Only deserialize from this after peeking a '"' byte! Otherwise it may /// deserialize invalid JSON successfully. struct MapKey<'a, R: 'a> {
de: &'a mut Deserializer<R>,
}
/// Iterator that deserializes a stream into multiple JSON values. /// /// A stream deserializer can be created from any JSON deserializer using the /// `Deserializer::into_iter` method. /// /// The data can consist of any JSON value. Values need to be a self-delineating value e.g. /// arrays, objects, or strings, or be followed by whitespace or a self-delineating value. /// /// ``` /// use serde_json::{Deserializer, Value}; /// /// fn main() { /// let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{} [0, 1, 2]"; /// /// let stream = Deserializer::from_str(data).into_iter::<Value>(); /// /// for value in stream { /// println!("{}", value.unwrap()); /// } /// } /// ``` pubstruct StreamDeserializer<'de, R, T> {
de: Deserializer<R>,
offset: usize,
failed: bool,
output: PhantomData<T>,
lifetime: PhantomData<&'de ()>,
}
impl<'de, R, T> StreamDeserializer<'de, R, T> where
R: read::Read<'de>,
T: de::Deserialize<'de>,
{ /// Create a JSON stream deserializer from one of the possible serde_json /// input sources. /// /// Typically it is more convenient to use one of these methods instead: /// /// - Deserializer::from_str(...).into_iter() /// - Deserializer::from_slice(...).into_iter() /// - Deserializer::from_reader(...).into_iter() pubfn new(read: R) -> Self { let offset = read.byte_offset();
StreamDeserializer {
de: Deserializer::new(read),
offset,
failed: false,
output: PhantomData,
lifetime: PhantomData,
}
}
/// Returns the number of bytes so far deserialized into a successful `T`. /// /// If a stream deserializer returns an EOF error, new data can be joined to /// `old_data[stream.byte_offset()..]` to try again. /// /// ``` /// let data = b"[0] [1] ["; /// /// let de = serde_json::Deserializer::from_slice(data); /// let mut stream = de.into_iter::<Vec<i32>>(); /// assert_eq!(0, stream.byte_offset()); /// /// println!("{:?}", stream.next()); // [0] /// assert_eq!(3, stream.byte_offset()); /// /// println!("{:?}", stream.next()); // [1] /// assert_eq!(7, stream.byte_offset()); /// /// println!("{:?}", stream.next()); // error /// assert_eq!(8, stream.byte_offset()); /// /// // If err.is_eof(), can join the remaining data to new data and continue. /// let remaining = &data[stream.byte_offset()..]; /// ``` /// /// *Note:* In the future this method may be changed to return the number of /// bytes so far deserialized into a successful T *or* syntactically valid /// JSON skipped over due to a type error. See [serde-rs/json#70] for an /// example illustrating this. /// /// [serde-rs/json#70]: https://github.com/serde-rs/json/issues/70 pubfn byte_offset(&self) -> usize { self.offset
}
// skip whitespaces, if any // this helps with trailing whitespaces, since whitespaces between // values are handled for us. matchself.de.parse_whitespace() {
Ok(None) => { self.offset = self.de.read.byte_offset();
None
}
Ok(Some(b)) => { // If the value does not have a clear way to show the end of the value // (like numbers, null, true etc.) we have to look for whitespace or // the beginning of a self-delineated value. let self_delineated_value = match b {
b'[' | b'"' | b'{' => true,
_ => false,
}; self.offset = self.de.read.byte_offset(); let result = de::Deserialize::deserialize(&mutself.de);
fn from_trait<'de, R, T>(read: R) -> Result<T> where
R: Read<'de>,
T: de::Deserialize<'de>,
{ letmut de = Deserializer::new(read); let value = tri!(de::Deserialize::deserialize(&mut de));
// Make sure the whole stream has been consumed.
tri!(de.end());
Ok(value)
}
/// Deserialize an instance of type `T` from an I/O stream of JSON. /// /// The content of the I/O stream is deserialized directly from the stream /// without being buffered in memory by serde_json. /// /// When reading from a source against which short reads are not efficient, such /// as a [`File`], you will want to apply your own buffering because serde_json /// will not buffer the input. See [`std::io::BufReader`]. /// /// It is expected that the input stream ends after the deserialized object. /// If the stream does not end, such as in the case of a persistent socket connection, /// this function will not return. It is possible instead to deserialize from a prefix of an input /// stream without looking for EOF by managing your own [`Deserializer`]. /// /// Note that counter to intuition, this function is usually slower than /// reading a file completely into memory and then applying [`from_str`] /// or [`from_slice`] on it. See [issue #160]. /// /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html /// [`std::io::BufReader`]: https://doc.rust-lang.org/std/io/struct.BufReader.html /// [`from_str`]: ./fn.from_str.html /// [`from_slice`]: ./fn.from_slice.html /// [issue #160]: https://github.com/serde-rs/json/issues/160 /// /// # Example /// /// Reading the contents of a file. /// /// ``` /// use serde::Deserialize; /// /// use std::error::Error; /// use std::fs::File; /// use std::io::BufReader; /// use std::path::Path; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn read_user_from_file<P: AsRef<Path>>(path: P) -> Result<User, Box<dyn Error>> { /// // Open the file in read-only mode with buffer. /// let file = File::open(path)?; /// let reader = BufReader::new(file); /// /// // Read the JSON contents of the file as an instance of `User`. /// let u = serde_json::from_reader(reader)?; /// /// // Return the `User`. /// Ok(u) /// } /// /// fn main() { /// # } /// # fn fake_main() { /// let u = read_user_from_file("test.json").unwrap(); /// println!("{:#?}", u); /// } /// ``` /// /// Reading from a persistent socket connection. /// /// ``` /// use serde::Deserialize; /// /// use std::error::Error; /// use std::net::{TcpListener, TcpStream}; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn read_user_from_stream(tcp_stream: TcpStream) -> Result<User, Box<dyn Error>> { /// let mut de = serde_json::Deserializer::from_reader(tcp_stream); /// let u = User::deserialize(&mut de)?; /// /// Ok(u) /// } /// /// fn main() { /// # } /// # fn fake_main() { /// let listener = TcpListener::bind("127.0.0.1:4000").unwrap(); /// /// for stream in listener.incoming() { /// println!("{:#?}", read_user_from_stream(stream.unwrap())); /// } /// } /// ``` /// /// # Errors /// /// This conversion can fail if the structure of the input does not match the /// structure expected by `T`, for example if `T` is a struct type but the input /// contains something other than a JSON map. It can also fail if the structure /// is correct but `T`'s implementation of `Deserialize` decides that something /// is wrong with the data, for example required struct fields are missing from /// the JSON map or some number is too big to fit in the expected primitive /// type. #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] pubfn from_reader<R, T>(rdr: R) -> Result<T> where
R: crate::io::Read,
T: de::DeserializeOwned,
{
from_trait(read::IoRead::new(rdr))
}
/// Deserialize an instance of type `T` from bytes of JSON text. /// /// # Example /// /// ``` /// use serde::Deserialize; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn main() { /// // The type of `j` is `&[u8]` /// let j = b" /// { /// \"fingerprint\": \"0xF9BA143B95FF6D82\", /// \"location\": \"Menlo Park, CA\" /// }"; /// /// let u: User = serde_json::from_slice(j).unwrap(); /// println!("{:#?}", u); /// } /// ``` /// /// # Errors /// /// This conversion can fail if the structure of the input does not match the /// structure expected by `T`, for example if `T` is a struct type but the input /// contains something other than a JSON map. It can also fail if the structure /// is correct but `T`'s implementation of `Deserialize` decides that something /// is wrong with the data, for example required struct fields are missing from /// the JSON map or some number is too big to fit in the expected primitive /// type. pubfn from_slice<'a, T>(v: &'a [u8]) -> Result<T> where
T: de::Deserialize<'a>,
{
from_trait(read::SliceRead::new(v))
}
/// Deserialize an instance of type `T` from a string of JSON text. /// /// # Example /// /// ``` /// use serde::Deserialize; /// /// #[derive(Deserialize, Debug)] /// struct User { /// fingerprint: String, /// location: String, /// } /// /// fn main() { /// // The type of `j` is `&str` /// let j = " /// { /// \"fingerprint\": \"0xF9BA143B95FF6D82\", /// \"location\": \"Menlo Park, CA\" /// }"; /// /// let u: User = serde_json::from_str(j).unwrap(); /// println!("{:#?}", u); /// } /// ``` /// /// # Errors /// /// This conversion can fail if the structure of the input does not match the /// structure expected by `T`, for example if `T` is a struct type but the input /// contains something other than a JSON map. It can also fail if the structure /// is correct but `T`'s implementation of `Deserialize` decides that something /// is wrong with the data, for example required struct fields are missing from /// the JSON map or some number is too big to fit in the expected primitive /// type. pubfn from_str<'a, T>(s: &'a str) -> Result<T> where
T: de::Deserialize<'a>,
{
from_trait(read::StrRead::new(s))
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.37 Sekunden
(vorverarbeitet am 2026-06-18)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.