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