aboutsummaryrefslogtreecommitdiffstats
path: root/src/json.rs
blob: 2816a1fe713a0f971d2ba44bbca4602d9a0b744c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use crate::prelude::*;

pub trait DeserializeJsonWithPath {
    fn json_with_path<T: serde::de::DeserializeOwned>(self) -> Result<T>;
}

impl DeserializeJsonWithPath for String {
    fn json_with_path<T: serde::de::DeserializeOwned>(self) -> Result<T> {
        let jd = &mut serde_json::Deserializer::from_str(&self);
        serde_path_to_error::deserialize(jd).context(crate::error::JSON)
    }
}

impl DeserializeJsonWithPath for reqwest::blocking::Response {
    fn json_with_path<T: serde::de::DeserializeOwned>(self) -> Result<T> {
        let bytes = self.bytes().context(crate::error::Reqwest)?;
        let jd = &mut serde_json::Deserializer::from_slice(&bytes);
        serde_path_to_error::deserialize(jd).context(crate::error::JSON)
    }
}

#[async_trait::async_trait]
pub trait DeserializeJsonWithPathAsync {
    async fn json_with_path<T: serde::de::DeserializeOwned>(
        self,
    ) -> Result<T>;
}

#[async_trait::async_trait]
impl DeserializeJsonWithPathAsync for reqwest::Response {
    async fn json_with_path<T: serde::de::DeserializeOwned>(
        self,
    ) -> Result<T> {
        let bytes = self.bytes().await.context(crate::error::Reqwest)?;
        let jd = &mut serde_json::Deserializer::from_slice(&bytes);
        serde_path_to_error::deserialize(jd).context(crate::error::JSON)
    }
}