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/// An item which can deserialized from a JSON serialization.
26pub trait JsonObject: JsonDeserialize {
27  /// Deserialize this item from an JSON-serialized blob.
28  ///
29  /// This will deserialize the object present without limitation. If a bound is desired, bound the
30  /// length of input or deserialize into types which define bounds.
31  ///
32  /// This method SHOULD NOT be overriden.
33  fn deserialize_object<'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  fn deserialize<'bytes, 'parent, B: BytesLike<'bytes>, S: Stack>(
44    value: Value<'bytes, 'parent, B, S>,
45  ) -> Result<Self, JsonError<'bytes, B, S>> {
46    if value.is_null()? {
47      return Ok(None);
48    }
49    T::deserialize(value).map(Some)
50  }
51}