core_json_traits/
option.rs

1use crate::{BytesLike, Stack, JsonError, Value, JsonDeserialize, JsonSerialize};
2
3impl<T: JsonDeserialize> JsonDeserialize for Option<T> {
4  /// This will accept `null` as a representation of `None`.
5  fn deserialize<'bytes, 'parent, B: BytesLike<'bytes>, S: Stack>(
6    value: Value<'bytes, 'parent, B, S>,
7  ) -> Result<Self, JsonError<'bytes, B, S>> {
8    if value.is_null()? {
9      return Ok(None);
10    }
11    T::deserialize(value).map(Some)
12  }
13}
14
15impl<T: JsonSerialize> JsonSerialize for Option<T> {
16  /// This will serialize `Some(value)` as `value` and `None` as `null`.
17  fn serialize(&self) -> impl Iterator<Item = char> {
18    self
19      .as_ref()
20      .map(|value| T::serialize(value))
21      .into_iter()
22      .flatten()
23      .chain(self.is_none().then(|| "null".chars()).into_iter().flatten())
24  }
25}