Skip to content

Instantly share code, notes, and snippets.

@r2p2
Created March 24, 2018 19:44
Show Gist options
  • Save r2p2/75f08247be4053a1e2abf3dc8ec577bf to your computer and use it in GitHub Desktop.
Save r2p2/75f08247be4053a1e2abf3dc8ec577bf to your computer and use it in GitHub Desktop.
// #1 version without Result as return type
fn from_json(data: &str) -> humans::Humans {
let mut humans = Vec::new();
let msg: Value = serde_json::from_str(data).expect("json error");
for human in msg["people"].as_array().unwrap().iter() {
humans.push(humans::Human::new(
human["name"].as_str().unwrap(),
human["craft"].as_str().unwrap(),
));
}
humans
}
/****************************************************************/
// #2 i guess i do it wrong
fn from_json(data: &str) -> Result<humans::Humans, String> {
let mut humans = Vec::new();
match serde_json::from_str(data) {
Ok(msg) => {
let msg : Value = msg;
match msg["people"].as_array() {
Some(people) => {
for person in people.iter() {
match person["name"].as_str() {
Some(name) => {
match person["craft"].as_str() {
Some(craft) => {
humans.push(humans::Human::new(name, craft));
},
None => {
return Err(String::from("'craft' field is missing"));
}
}
},
None => {
return Err(String::from("'name' field is missing"));
}
}
}
},
None => {
return Err(String::from("'people' field is missing"));
}
}
},
Err(reason) => {
return Err(String::from("Unable to deserialize json data: ") + reason.description());
}
}
Ok(humans)
}
/****************************************************************/
// #3 maybe better?
fn from_json(data: &str) -> Result<humans::Humans, String> {
let mut humans = Vec::new();
let msg: Value = match serde_json::from_str(data) {
Ok(msg) => msg,
Err(reason) => {
return Err(String::from("Unable to deserialize json data: ") + reason.description())
}
};
let people = match msg["people"].as_array() {
Some(people) => people,
None => return Err(String::from("'people' field is missing")),
};
for person in people.iter() {
let name = match person["name"].as_str() {
Some(name) => name,
None => return Err(String::from("'name' field is missing")),
};
let craft = match person["craft"].as_str() {
Some(craft) => craft,
None => return Err(String::from("'craft' field is missing")),
};
humans.push(humans::Human::new(name, craft));
}
Ok(humans)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment