json_elem/
jsonelem.rs

1use std::{collections::HashMap, fmt::Display};
2
3use serde_derive::{Deserialize, Serialize};
4
5use crate::error::Error;
6
7/// A list of JsonElem type.
8#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
9#[serde(untagged)]
10pub enum JsonElem {
11    Null,
12    Integer(i32),
13    Float(f64),
14    Bool(bool),
15    String(String),
16    Vec(Vec<JsonElem>),
17    HashMap(HashMap<String, JsonElem>),
18}
19
20impl JsonElem {
21    /// Converts from any struct T that implements serde::Serialize trait into
22    /// a JsonElem type.
23    pub fn convert_from<T: serde::Serialize>(value: &T) -> Result<Self, Error> {
24        let val = serde_json::to_string(&value).map_err(Error::SerdeJson)?;
25        let val: JsonElem = serde_json::from_str(&val).map_err(Error::SerdeJson)?;
26        Ok(val)
27    }
28    /// Converts from any JsonElem to any T that implements serde::Deserialize trait.
29    pub fn convert_to<T: serde::de::DeserializeOwned>(&self) -> Result<T, Error> {
30        let val = serde_json::to_string(&self).map_err(Error::SerdeJson)?;
31        let val: T = serde_json::from_str(&val).map_err(Error::SerdeJson)?;
32        Ok(val)
33    }
34
35    pub fn print(&self, indent: usize) {
36        print!("result : ");
37        self.print_recursive(indent);
38    }
39
40    fn print_recursive(&self, indent: usize) {
41        match self {
42            JsonElem::Null => println!("null"),
43            JsonElem::Bool(b) => println!(": b {}", b),
44            JsonElem::Integer(n) => println!(": i {}", n),
45            JsonElem::String(s) => println!(": {}", s),
46            JsonElem::Vec(arr) => {
47                println!("List");
48                for (n, element) in arr.iter().enumerate() {
49                    print!("{}{}", " ".repeat(indent + 2), n);
50                    element.print_recursive(indent + 2);
51                }
52            }
53            JsonElem::Float(f) => println!(": f {}", f),
54            JsonElem::HashMap(obj) => {
55                println!("Map");
56                for (key, val) in obj.iter() {
57                    print!("{}{} : ", " ".repeat(indent + 2), key);
58                    val.print_recursive(indent + 2);
59                }
60            }
61        }
62    }
63}
64
65/// Converts from String to JsonElem
66impl TryFrom<&str> for JsonElem {
67    type Error = Error;
68
69    fn try_from(value: &str) -> Result<Self, Self::Error> {
70        serde_json::from_str(value).map_err(Error::SerdeJson)
71    }
72}
73
74/// Converts from Bytes to JsonElem
75impl TryFrom<&[u8]> for JsonElem {
76    type Error = Error;
77
78    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
79        serde_json::from_slice(value).map_err(Error::SerdeJson)
80    }
81}
82
83/// Converts from JsonElem to String
84impl TryInto<String> for JsonElem {
85    type Error = Error;
86
87    fn try_into(self) -> Result<String, Self::Error> {
88        serde_json::to_string(&self).map_err(Error::SerdeJson)
89    }
90}
91
92/// Converts from JsonElem to Bytes
93impl TryInto<Vec<u8>> for JsonElem {
94    type Error = Error;
95
96    fn try_into(self) -> Result<Vec<u8>, Self::Error> {
97        serde_json::to_vec(&self).map_err(Error::SerdeJson)
98    }
99}
100
101impl Display for JsonElem {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            JsonElem::Null => write!(f, "{}", JsonElem::Null),
105            JsonElem::Integer(val) => write!(f, "{}", val),
106            JsonElem::Float(val) => write!(f, "{}", val),
107            JsonElem::Bool(val) => write!(f, "{}", val),
108            JsonElem::String(val) => write!(f, "{}", val),
109            JsonElem::Vec(val) => write!(f, "{:?}", val),
110            JsonElem::HashMap(val) => write!(f, "{:?}", val),
111        }
112    }
113}