1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
use std::collections::BTreeMap; use { JsonResult, JsonError }; #[derive(Debug, PartialEq)] pub enum JsonValue { String(String), Number(f64), Boolean(bool), Null, Object(BTreeMap<String, JsonValue>), Array(Vec<JsonValue>), } impl JsonValue { pub fn new_object() -> JsonValue { JsonValue::Object(BTreeMap::new()) } pub fn new_array() -> JsonValue { JsonValue::Array(Vec::new()) } pub fn is_string(&self) -> bool { match *self { JsonValue::String(_) => true, _ => false, } } pub fn is_number(&self) -> bool { match *self { JsonValue::Number(_) => true, _ => false, } } pub fn is_boolean(&self) -> bool { match *self { JsonValue::Boolean(_) => true, _ => false, } } pub fn is_null(&self) -> bool { match *self { JsonValue::Null => true, _ => false, } } pub fn is_object(&self) -> bool { match *self { JsonValue::Object(_) => true, _ => false, } } pub fn is_array(&self) -> bool { match *self { JsonValue::Array(_) => true, _ => false, } } #[must_use] pub fn put<T>(&mut self, key: &str, value: T) -> JsonResult<()> where T: Into<JsonValue> { match *self { JsonValue::Object(ref mut btree) => { btree.insert(key.into(), value.into()); Ok(()) }, _ => Err(JsonError::wrong_type("Object")) } } pub fn get(&self, key: &str) -> JsonResult<&JsonValue> { match *self { JsonValue::Object(ref btree) => match btree.get(key) { Some(value) => Ok(value), _ => Err(JsonError::undefined(key)) }, _ => Err(JsonError::wrong_type("Object")) } } }