serde_utils/
json_str.rs

1//! Serialize a datatype as a JSON-blob within a single string.
2use serde::{
3    de::{DeserializeOwned, Error as _},
4    ser::Error as _,
5    Deserialize, Deserializer, Serialize, Serializer,
6};
7
8/// Serialize as a JSON object within a string.
9pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
10where
11    S: Serializer,
12    T: Serialize,
13{
14    serializer.serialize_str(&serde_json::to_string(value).map_err(S::Error::custom)?)
15}
16
17/// Deserialize a JSON object embedded in a string.
18pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
19where
20    D: Deserializer<'de>,
21    T: DeserializeOwned,
22{
23    let json_str = String::deserialize(deserializer)?;
24    serde_json::from_str(&json_str).map_err(D::Error::custom)
25}
26
27#[cfg(test)]
28mod test {
29    use serde::{Deserialize, Serialize};
30
31    #[derive(Debug, PartialEq, Serialize, Deserialize)]
32    struct Wrapper {
33        val_1: String,
34        val_2: u8,
35        val_3: Vec<u8>,
36        val_4: Option<u32>,
37    }
38
39    #[test]
40    fn encoding() {
41        assert_eq!(
42            &serde_json::to_string(&Wrapper {
43                val_1: "Test".to_string(),
44                val_2: 5,
45                val_3: vec![9],
46                val_4: Some(10)
47            })
48            .unwrap(),
49            "{\"val_1\":\"Test\",\"val_2\":5,\"val_3\":[9],\"val_4\":10}"
50        );
51        assert_eq!(
52            &serde_json::to_string(&Wrapper {
53                val_1: "Test".to_string(),
54                val_2: 5,
55                val_3: vec![9],
56                val_4: None
57            })
58            .unwrap(),
59            "{\"val_1\":\"Test\",\"val_2\":5,\"val_3\":[9],\"val_4\":null}"
60        );
61    }
62
63    #[test]
64    fn decoding() {
65        assert_eq!(
66            serde_json::from_str::<Wrapper>(
67                "{\"val_1\":\"Test\",\"val_2\":5,\"val_3\":[9],\"val_4\":10}"
68            )
69            .unwrap(),
70            Wrapper {
71                val_1: "Test".to_string(),
72                val_2: 5,
73                val_3: vec![9],
74                val_4: Some(10)
75            },
76        );
77        assert_eq!(
78            serde_json::from_str::<Wrapper>(
79                "{\"val_1\":\"Test\",\"val_2\":5,\"val_3\":[9],\"val_4\":null}"
80            )
81            .unwrap(),
82            Wrapper {
83                val_1: "Test".to_string(),
84                val_2: 5,
85                val_3: vec![9],
86                val_4: None
87            },
88        );
89
90        // Violating type constraints.
91        serde_json::from_str::<Wrapper>("{\"val_1\":1,\"val_2\":5,\"val_3\":[9],\"val_4\":null}")
92            .unwrap_err();
93        serde_json::from_str::<Wrapper>("{\"val_1\":\"Test\",\"val_2\":5,\"val_4\":null}")
94            .unwrap_err();
95    }
96}