core_json_traits/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![deny(missing_docs)]
4#![no_std]
5
6#[cfg(feature = "alloc")]
7extern crate alloc;
8
9pub use core_json::*;
10
11mod primitives;
12mod sequences;
13
14/// An item which can be deserialized from a `Value`.
15///
16/// This will deserialize the object present without limitation. This should be kept in mind when
17/// deserializing into types which allocate.
18pub trait JsonDeserialize: Sized {
19  /// Decode this item from a `Value`.
20  fn deserialize<'bytes, 'parent, B: BytesLike<'bytes>, S: Stack>(
21    value: Value<'bytes, 'parent, B, S>,
22  ) -> Result<Self, JsonError<'bytes, B, S>>;
23}
24
25/// A structure which can deserialized from a JSON serialization.
26pub trait JsonStructure: JsonDeserialize {
27  /// Deserialize this structure from an JSON-serialized blob.
28  ///
29  /// This will deserialize the structure present without limitation. If a bound is desired, bound
30  /// the length of input or deserialize into types which define bounds.
31  ///
32  /// This method SHOULD NOT be overriden.
33  fn deserialize_structure<'bytes, B: BytesLike<'bytes>, S: Stack>(
34    json: B,
35  ) -> Result<Self, JsonError<'bytes, B, S>> {
36    let mut json = Deserializer::new(json)?;
37    let value = json.value()?;
38    Self::deserialize(value)
39  }
40}
41
42impl<T: JsonDeserialize> JsonDeserialize for Option<T> {
43  /// This will accept `null` as a representation of `None`.
44  fn deserialize<'bytes, 'parent, B: BytesLike<'bytes>, S: Stack>(
45    value: Value<'bytes, 'parent, B, S>,
46  ) -> Result<Self, JsonError<'bytes, B, S>> {
47    if value.is_null()? {
48      return Ok(None);
49    }
50    T::deserialize(value).map(Some)
51  }
52}
53
54#[cfg(feature = "alloc")]
55use alloc::string::String;
56#[cfg(feature = "alloc")]
57impl JsonDeserialize for String {
58  fn deserialize<'bytes, 'parent, B: BytesLike<'bytes>, S: Stack>(
59    value: Value<'bytes, 'parent, B, S>,
60  ) -> Result<Self, JsonError<'bytes, B, S>> {
61    value.to_str()?.collect()
62  }
63}