serde_helpers/
json.rs

1use serde::{Deserialize, Serialize};
2use serde_json;
3
4use Error;
5
6pub trait DeserializeJson<'a>: Deserialize<'a> {
7    fn from_json_str(s: &'a str) -> Result<Self, Error> {
8        serde_json::from_str(s).map_err(Error::from)
9    }
10
11    fn from_json_slice(v: &'a [u8]) -> Result<Self, Error> {
12        serde_json::from_slice(v).map_err(Error::from)
13    }
14}
15
16impl<'a, T> DeserializeJson<'a> for T
17where
18    T: Deserialize<'a>,
19{
20}
21
22pub trait SerializeJson: Serialize {
23    fn to_json_string(&self) -> Result<String, Error> {
24        serde_json::to_string(self).map_err(Error::from)
25    }
26
27    fn to_json_string_pretty(&self) -> Result<String, Error> {
28        serde_json::to_string_pretty(self).map_err(Error::from)
29    }
30
31    fn to_json_vec(&self) -> Result<Vec<u8>, Error> {
32        serde_json::to_vec(self).map_err(Error::from)
33    }
34
35    fn to_json_vec_pretty(&self) -> Result<Vec<u8>, Error> {
36        serde_json::to_vec_pretty(self).map_err(Error::from)
37    }
38}
39
40impl<T> SerializeJson for T
41where
42    T: Serialize,
43{
44}