aboutsummaryrefslogtreecommitdiff
path: root/src/tw/user.rs
blob: 86fbe3f6e3989bd4273e4e199b3f69316344e504 (plain)
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
extern crate serde_json;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct User {
    pub id: String,
    pub name: String,
    pub handle: String
}

impl Default for User {
    fn default() -> User {
        User {
            id: "".to_owned(),
            name: "_default_".to_owned(),
            handle: "_default_".to_owned()
        }
    }
}

impl User {
    pub fn from_json(json: serde_json::Value) -> Result<User, String> {
        if let serde_json::Value::Object(json_map) = json {
            if let (
                Some(id_str),
                Some(name),
                Some(screen_name)
            ) = (
                json_map.get("id_str").and_then(|x| x.as_str()),
                json_map.get("name").and_then(|x| x.as_str()),
                json_map.get("screen_name").and_then(|x| x.as_str())
            ) {
                Ok(User {
                    id: id_str.to_owned(),
                    name: name.to_owned(),
                    handle: screen_name.to_owned()
                })
            } else {
                Err("user json missing one of id_str, name, screen_name".to_owned())
            }
        } else {
            Err(format!("Invalid json: {:?}", json))
        }
    }
}