|
105 | 105 | //! };
|
106 | 106 | //!
|
107 | 107 | //! // Serialize using `json::encode`
|
108 |
| -//! let encoded = json::encode(&object); |
| 108 | +//! let encoded = json::encode(&object).unwrap(); |
109 | 109 | //!
|
110 | 110 | //! // Deserialize using `json::decode`
|
111 | 111 | //! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
|
|
151 | 151 | //! uid: 1,
|
152 | 152 | //! dsc: "test".to_string(),
|
153 | 153 | //! val: num.to_json(),
|
154 |
| -//! }); |
| 154 | +//! }).unwrap(); |
155 | 155 | //! println!("data: {}", data);
|
156 | 156 | //! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
|
157 | 157 | //! }
|
@@ -324,13 +324,13 @@ pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
|
324 | 324 | }
|
325 | 325 |
|
326 | 326 | /// Shortcut function to encode a `T` into a JSON `String`
|
327 |
| -pub fn encode<T: ::Encodable>(object: &T) -> string::String { |
| 327 | +pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError> { |
328 | 328 | let mut s = String::new();
|
329 | 329 | {
|
330 | 330 | let mut encoder = Encoder::new(&mut s);
|
331 |
| - let _ = object.encode(&mut encoder); |
| 331 | + try!(object.encode(&mut encoder)); |
332 | 332 | }
|
333 |
| - s |
| 333 | + Ok(s) |
334 | 334 | }
|
335 | 335 |
|
336 | 336 | impl fmt::Show for ErrorCode {
|
@@ -3552,6 +3552,26 @@ mod tests {
|
3552 | 3552 | let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
|
3553 | 3553 | }
|
3554 | 3554 |
|
| 3555 | + #[test] |
| 3556 | + fn test_hashmap_with_enum_key() { |
| 3557 | + use std::collections::HashMap; |
| 3558 | + use json; |
| 3559 | + #[derive(RustcEncodable, Eq, Hash, PartialEq)] |
| 3560 | + enum Enum { |
| 3561 | + Foo, |
| 3562 | + #[allow(dead_code)] |
| 3563 | + Bar, |
| 3564 | + } |
| 3565 | + let mut map = HashMap::new(); |
| 3566 | + map.insert(Enum::Foo, 0); |
| 3567 | + let result = json::encode(&map); |
| 3568 | + match result.unwrap_err() { |
| 3569 | + EncoderError::BadHashmapKey => (), |
| 3570 | + _ => panic!("expected bad hash map key") |
| 3571 | + } |
| 3572 | + //assert_eq!(&enc[], r#"{"Foo": 0}"#); |
| 3573 | + } |
| 3574 | + |
3555 | 3575 | #[test]
|
3556 | 3576 | fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
|
3557 | 3577 | use std::collections::HashMap;
|
|
0 commit comments