restless_data/
json.rs

1use crate::{Decodable, Encodable};
2use serde::{de::DeserializeOwned, Serialize};
3use serde_json::{from_slice, to_vec, Error};
4use std::borrow::Cow;
5
6/// Encode and decode data as JSON using `serde_json`.
7#[cfg(any(doc, feature = "json"))]
8#[derive(Clone, Debug)]
9pub struct Json<T>(pub T);
10
11impl<T: Serialize> Encodable for Json<T> {
12    fn encode(&self) -> Vec<u8> {
13        to_vec(&self.0).unwrap()
14    }
15
16    fn content_type(&self) -> Option<Cow<'_, str>> {
17        Some("application/json".into())
18    }
19}
20
21impl<T: DeserializeOwned> Decodable for super::Json<T> {
22    type Target = T;
23    type Error = Error;
24
25    fn decode(data: &[u8]) -> Result<Self::Target, Self::Error> {
26        from_slice(data)
27    }
28}