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
87
88
89
90
91
92
93
94
95
96
use serialize::json::Json;
use serialize::json::Object;
use super::error::InvalidJsonError;
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
data: Json
}
impl Response {
pub fn for_fail(msg: &str) -> Response {
let mut obj = Object::new();
obj.insert("success".to_string(), Json::Boolean(false));
obj.insert("reason".to_string(), Json::String(msg.to_string()));
Response { data: Json::Object(obj) }
}
pub fn for_success() -> Response {
let mut obj = Object::new();
obj.insert("success".to_string(), Json::Boolean(true));
Response { data: Json::Object(obj) }
}
pub fn from_json(data: &Json) -> Result<Response, InvalidJsonError> {
Ok(Response { data: data.clone() })
}
pub fn get_or<'a>(&'a self, prop: &'a str, default: &'a Json) -> &'a Json {
match self.get(prop) {
Some(val) => val,
None => default,
}
}
pub fn get<'a>(&'a self, prop: &'a str) -> Option<&'a Json> {
match self.data {
Json::Object(ref obj) => {
obj.get(prop)
},
_ => None,
}
}
pub fn get_str<'a>(&'a self, prop: &'a str) -> Option<&'a str> {
match self.get(prop) {
Some(&Json::String(ref s)) => Some(&s[..]),
_ => None,
}
}
pub fn get_str_or<'a>(&'a self, prop: &'a str, default: &'a str) -> &'a str {
match self.get_str(prop) {
Some(s) => s,
None => default,
}
}
pub fn has(&self, prop: &str) -> bool {
match self.get_str(prop) {
Some(_) => true,
None => false
}
}
pub fn has_success(&self) -> bool {
match self.get("success") {
Some(&Json::Boolean(true)) => true,
_ => false,
}
}
}