serde_valid/json/to_json_string.rs
1pub trait ToJsonString {
2 /// Convert to json string.
3 ///
4 /// ```rust
5 /// use serde::Serialize;
6 /// use serde_valid::json::ToJsonString;
7 /// use serde_valid::Validate;
8 ///
9 /// #[derive(Debug, Validate, Serialize)]
10 /// struct TestStruct {
11 /// #[validate(maximum = 100)]
12 /// val: i32,
13 /// }
14 /// let s = TestStruct { val: 10 };
15 ///
16 /// assert!(s.to_json_string().is_ok());
17 /// ```
18 fn to_json_string(&self) -> Result<String, serde_json::Error>;
19
20 /// Convert to json pretty string.
21 ///
22 /// ```rust
23 /// use serde::Serialize;
24 /// use serde_valid::json::ToJsonString;
25 /// use serde_valid::Validate;
26 ///
27 /// #[derive(Debug, Validate, Serialize)]
28 /// struct TestStruct {
29 /// #[validate(maximum = 100)]
30 /// val: i32,
31 /// }
32 /// let s = TestStruct { val: 10 };
33 ///
34 /// assert!(s.to_json_string_pretty().is_ok());
35 /// ```
36 fn to_json_string_pretty(&self) -> Result<String, serde_json::Error>;
37}
38
39impl<T> ToJsonString for T
40where
41 T: serde::Serialize + crate::Validate,
42{
43 fn to_json_string(&self) -> Result<String, serde_json::Error> {
44 serde_json::to_string(self)
45 }
46
47 fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
48 serde_json::to_string_pretty(self)
49 }
50}
51
52impl ToJsonString for serde_json::Value {
53 fn to_json_string(&self) -> Result<String, serde_json::Error> {
54 serde_json::to_string(self)
55 }
56
57 fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
58 serde_json::to_string_pretty(self)
59 }
60}