tiny_json_rs/serializer/
mod.rs1pub mod deserializers;
2pub mod serializers;
3
4pub use crate::lexer::{Lexer, LexerError, Token};
5pub use crate::mapper::{Mapper, MapperError, Value};
6use alloc::format;
7use alloc::string::String;
8use core::str::FromStr;
9
10pub trait Deserialize: Sized {
11 fn deserialize(value: Option<&Value>) -> Result<Self, DecodeError>;
12}
13
14pub trait Serialize: Sized {
15 fn serialize(&self) -> Value;
16}
17
18#[derive(Debug)]
19pub enum DecodeError {
20 MapperError(MapperError),
21 LexerError(LexerError),
22 UnexpectedType,
23 ParseError(String),
24}
25
26impl From<MapperError> for DecodeError {
27 fn from(error: MapperError) -> Self {
28 DecodeError::MapperError(error)
29 }
30}
31
32impl From<LexerError> for DecodeError {
33 fn from(error: LexerError) -> Self {
34 DecodeError::LexerError(error)
35 }
36}
37
38impl Token {
39 pub fn to<T>(&self) -> Result<T, DecodeError>
40 where
41 T: FromStr,
42 {
43 T::from_str(&self.literal).map_err(|_| {
44 DecodeError::ParseError(format!(
45 "Could not parse {} to {}",
46 self.literal,
47 core::any::type_name::<T>()
48 ))
49 })
50 }
51}
52
53impl Value {
54 pub fn get_value<T>(&self, key: &str) -> Result<T, DecodeError>
55 where
56 T: Deserialize,
57 {
58 let option_val = match self {
59 Value::Object(object) => object.get(key),
60 _ => None,
61 };
62
63 let res = T::deserialize(option_val)?;
64
65 Ok(res)
66 }
67
68 pub fn encode_json(&self) -> String {
69 let mut output = String::new();
70 match self {
71 Value::Object(object) => {
72 output += "{";
73 let mut first = true;
74 for (key, value) in object {
75 if !first {
76 output += ",";
77 }
78 first = false;
79 output += &format!("\"{}\":{}", key, value.encode_json());
80 }
81 output += "}";
82 }
83 Value::Token(t) => match t.token_type {
84 crate::lexer::TokenType::String(_) => {
85 output += &format!("\"{}\"", t.literal);
86 }
87 _ => {
88 output += &format!("{}", t.literal);
89 }
90 },
91 Value::Array(a) => {
92 output += "[";
93 let mut first = true;
94 for value in a {
95 if !first {
96 output += ",";
97 }
98 first = false;
99 output += &format!("{}", value.encode_json());
100 }
101 output += "]";
102 }
103 }
104
105 output
106 }
107}
108
109pub fn decode<T>(input_str: String) -> Result<T, DecodeError>
110where
111 T: Deserialize,
112{
113 let mut lexer = Lexer::new(input_str);
114 let tokens = lexer.tokenize()?;
115 let mut mapper = Mapper::new(tokens);
116 let object = mapper.parse_object()?;
117 let value = Value::Object(object);
118 Ok(T::deserialize(Some(&value))?)
119}
120
121pub fn encode<T>(input: T) -> String
122where
123 T: Serialize,
124{
125 input.serialize().encode_json()
126}
127
128#[cfg(test)]
129pub mod test {
130 use crate::{Deserialize, Serialize};
131 use alloc::string::{String, ToString};
132 use alloc::vec::Vec;
133
134 use crate::alloc::borrow::ToOwned;
135 use crate::mapper;
136 use crate::serializer;
137
138 #[derive(Debug, PartialEq, Deserialize, Serialize)]
139 pub struct A {
140 #[Rename = "aJson"]
141 pub a: i32,
142 pub b: String,
143 }
144
145 #[derive(Debug, PartialEq, Deserialize, Serialize)]
146 pub struct B {
147 pub a: i32,
148 pub b: Vec<String>,
149 }
150
151 #[derive(Debug, PartialEq, Deserialize, Serialize)]
152 pub struct C {
153 pub a: i32,
154 pub b: Vec<A>,
155 }
156
157 #[test]
158 pub fn test_deserialize() {
159 const JSON: &str = r#"
160 {
161 "aJson": 1,
162 "b": "Hello"
163 }"#;
164
165 let a: A = super::decode(JSON.to_string()).unwrap();
166 assert_eq!(a.a, 1);
167 assert_eq!(a.b, "Hello");
168 }
169
170 #[test]
171 pub fn test_desserialize_vec() {
172 const JSON: &str = r#"
173 {
174 "a": 1,
175 "b": ["Hello","world"]
176 }"#;
177
178 let a: B = super::decode(JSON.to_string()).unwrap();
179 assert_eq!(a.a, 1);
180 assert_eq!(a.b.len(), 2);
181 assert_eq!(a.b[0], "Hello");
182 assert_eq!(a.b[1], "world");
183 }
184
185 #[test]
186 pub fn test_encode_json() {
187 let a = A {
188 a: 1,
189 b: "Hello".to_string(),
190 };
191
192 let json = super::encode(a);
193 assert_eq!(json, r#"{"aJson":1,"b":"Hello"}"#);
194 }
195
196 #[test]
197 pub fn test_nested() {
198 const JSON: &str = r#"
199 {
200 "a": 1,
201 "b": [
202 {
203 "aJson": 1,
204 "b": "Hello"
205 },
206 {
207 "aJson": 2,
208 "b": "World"
209 }
210 ]
211 }"#;
212
213 let a: C = super::decode(JSON.to_string()).unwrap();
214 assert_eq!(a.a, 1);
215 assert_eq!(a.b.len(), 2);
216 assert_eq!(a.b[0].a, 1);
217 assert_eq!(a.b[0].b, "Hello");
218 assert_eq!(a.b[1].a, 2);
219 assert_eq!(a.b[1].b, "World");
220 }
221}