Initial support for json deserializing enums

This commit is contained in:
Erick Tryzelaar 2014-05-29 08:02:06 -07:00
parent 27a914cdcf
commit cdf8e0820c

58
json.rs
View File

@ -2500,6 +2500,10 @@ impl ToJson for bool {
fn to_json(&self) -> Json { Boolean(*self) } fn to_json(&self) -> Json { Boolean(*self) }
} }
impl<'a> ToJson for &'a str {
fn to_json(&self) -> Json { String(self.to_string()) }
}
impl ToJson for String { impl ToJson for String {
fn to_json(&self) -> Json { String((*self).clone()) } fn to_json(&self) -> Json { String((*self).clone()) }
} }
@ -2652,6 +2656,22 @@ mod tests {
} }
} }
impl ToJson for Animal {
fn to_json(&self) -> Json {
match *self {
Dog => String("Dog".to_string()),
Frog(ref x0, x1) => {
Object(
treemap!(
"variant".to_string() => "Frog".to_json(),
"fields".to_string() => List(vec!(x0.to_json(), x1.to_json()))
)
)
}
}
}
}
#[deriving(Eq, Show)] #[deriving(Eq, Show)]
struct Inner { struct Inner {
a: (), a: (),
@ -3038,6 +3058,7 @@ mod tests {
} }
*/ */
// FIXME (#5527): these could be merged once UFCS is finished.
fn test_parse_err< fn test_parse_err<
'a, 'a,
T: Eq + Show + de::Deserializable<ParserError, Parser<str::Chars<'a>>> T: Eq + Show + de::Deserializable<ParserError, Parser<str::Chars<'a>>>
@ -3067,6 +3088,10 @@ mod tests {
for value in errors.iter() { for value in errors.iter() {
let v: T = from_json(value.to_json()).unwrap(); let v: T = from_json(value.to_json()).unwrap();
assert_eq!(v, *value); assert_eq!(v, *value);
// Make sure we can round trip back to `Json`.
let v: Json = from_json(value.to_json()).unwrap();
assert_eq!(v, value.to_json());
} }
} }
@ -3476,26 +3501,25 @@ mod tests {
/* /*
#[test] #[test]
fn test_decode_enum() { fn test_parse_enum() {
let value: Result<Animal, ParserError> = from_iter("\"Dog\"".chars()); test_parse_ok([
assert_eq!(value, Ok(Dog)); ("\"Dog\"", Dog),
(
let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"; "{\"variant\": \"Frog\", \"fields\": [\"Henry\", 349}",
let value: Result<Animal, ParserError> = from_iter(s.chars()); Frog("Henry".to_string(), 349),
assert_eq!(value, Ok(Frog("Henry".to_string(), 349))); )
]);
let mut decoder = Decoder::new(from_str("\"Dog\"").unwrap());
let value: Animal = Decodable::decode(&mut decoder).unwrap();
assert_eq!(value, Dog);
let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
let mut decoder = Decoder::new(from_str(s).unwrap());
let value: Animal = Decodable::decode(&mut decoder).unwrap();
assert_eq!(value, Frog("Henry".to_string(), 349));
assert_eq!(value, Dog);
} }
*/ */
#[test]
fn test_json_deserialize_enum() {
test_json_deserialize_ok([
Dog,
Frog("Henry".to_string(), 349),
]);
}
/* /*
#[test] #[test]
fn test_decode_map() { fn test_decode_map() {