ytmapi_rs/
json.rs

1//! This module contains the representation of Json exposed in the default
2//! public API in this library.
3use serde::{de::DeserializeOwned, Deserialize, Serialize};
4use serde_json::Value;
5
6/// Basic representation of any valid Json value, wrapping a
7/// `serde_json::Value`. For use if you are implementing [`crate::query::Query`]
8/// from scratch. To parse this value, you can utilise the Serialize /
9/// Deserialize traits, the [`from_json`] function to convert to a concrete
10/// type, or enable the `serde_json` feature to expose the internals via feature
11/// gated function `Json::into_inner`.
12/// # Note
13/// This struct does not implement Deserializer, as implementation is more
14/// complex than this thin wrapper.
15#[derive(Clone, PartialEq, Hash, Serialize, Deserialize)]
16#[serde(transparent)]
17pub struct Json {
18    pub(crate) inner: Value,
19}
20
21/// Interpret Json as an instance of type T.
22/// See [`crate::parse`] for a usage example.
23pub fn from_json<T: DeserializeOwned>(json: Json) -> crate::Result<T> {
24    serde_json::from_value(json.inner).map_err(|e| crate::Error::from(std::io::Error::from(e)))
25}
26
27impl std::fmt::Debug for Json {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        self.inner.fmt(f)
30    }
31}
32
33impl Json {
34    /// Extract the inner `serde_json::Value`
35    #[cfg(feature = "serde_json")]
36    #[cfg_attr(docsrs, doc(cfg(feature = "serde_json")))]
37    pub fn into_inner(self) -> serde_json::Value {
38        self.inner
39    }
40    pub(crate) fn new(json: serde_json::Value) -> Self {
41        Self { inner: json }
42    }
43}