rust_web_server/json/array/object/
mod.rs

1use crate::core::New;
2use crate::json::array::RawUnprocessedJSONArray;
3use crate::json::object::{FromJSON, ToJSON};
4use crate::symbol::SYMBOL;
5
6#[cfg(test)]
7mod example_multi_nested_object;
8#[cfg(test)]
9mod example_multi_nested_object_with_asserts;
10
11pub struct JSONArrayOfObjects<T> {
12    _item: T, // added to eliminate compiler error
13}
14
15impl<T: New> JSONArrayOfObjects<T> {
16    pub fn new() -> T {
17        T::new()
18    }
19}
20
21impl<T: ToJSON> JSONArrayOfObjects<T> {
22    pub fn to_json(items : &Vec<T>) -> Result<String, String> {
23        let mut json_vec = vec![];
24        json_vec.push(SYMBOL.opening_square_bracket.to_string());
25        for (pos, item) in items.iter().enumerate() {
26            json_vec.push(item.to_json_string());
27            if pos != items.len() - 1 {
28                json_vec.push(SYMBOL.comma.to_string());
29                json_vec.push(SYMBOL.new_line_carriage_return.to_string());
30            }
31        }
32        json_vec.push(SYMBOL.closing_square_bracket.to_string());
33
34        let result = json_vec.join(SYMBOL.empty_string);
35        Ok(result)
36    }
37}
38
39impl<T: FromJSON + New> JSONArrayOfObjects<T> {
40    pub fn from_json(json : String) -> Result<Vec<T>, String> {
41        let items = RawUnprocessedJSONArray::split_into_vector_of_strings(json).unwrap();
42        let mut list: Vec<T> = vec![];
43        for item in items {
44            let mut object = T::new();
45            object.parse(item).unwrap();
46            list.push(object);
47        }
48        Ok(list)
49    }
50}