Skip to content

Instantly share code, notes, and snippets.

@jcrubino
Created January 10, 2015 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcrubino/3b086d816bf469478a43 to your computer and use it in GitHub Desktop.
Save jcrubino/3b086d816bf469478a43 to your computer and use it in GitHub Desktop.
// http://is.gd/gWewbP
extern mod extra;
use extra::treemap::TreeMap;
use extra::json::ToJson;
use extra::serialize::Decodable;
use json = extra::json;
// structs are required for decoding a JSON object into a Rust object
#[deriving(Decodable)]
struct Person {
name: ~str,
age: int
}
fn main() {
// messing around with TreeMap
println("Creating a TreeMap object");
let mut person = ~TreeMap::new();
person.insert(~"name", (~"Rudolf").to_json());
person.insert(~"age", (26 as int).to_json());
println("Finding data in the TreeMap object");
let name = person.find(&~"name").unwrap();
let age = person.find(&~"age").unwrap();
println(format!("name: {:s}", name.to_str()));
println(format!("age: {:s}", age.to_str()));
let non_existent_attr = person.find(&~"HAHAHA");
match non_existent_attr {
None => println("HAHAHA doesn't exist"),
_ => println(format!("HAHAHA: {:s}", non_existent_attr.unwrap().to_str()))
}
// serializing/deserializing
let mut me = ~TreeMap::new();
me.insert(~"name", (~"Awesome Man").to_json());
me.insert(~"age", (26 as int).to_json());
let serialized = json::Object(me).to_str();
println(serialized);
let mut decoder = json::Decoder::new(json::from_str(serialized).unwrap());
let deserialized: Person = Decodable::decode(&mut decoder);
println(format!("Hi I'm {:s} and I'm {:d} years old.", deserialized.name, deserialized.age));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment