Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions src/libserialize/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
//! };
//!
//! // Serialize using `json::encode`
//! let encoded = json::encode(&object);
//! let encoded = json::encode(&object).unwrap();
//!
//! // Deserialize using `json::decode`
//! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap();
Expand Down Expand Up @@ -143,7 +143,7 @@
//! uid: 1,
//! dsc: "test".to_string(),
//! val: num.to_json(),
//! });
//! }).unwrap();
//! println!("data: {}", data);
//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"};
//! }
Expand Down Expand Up @@ -316,13 +316,13 @@ pub fn decode<T: ::Decodable>(s: &str) -> DecodeResult<T> {
}

/// Shortcut function to encode a `T` into a JSON `String`
pub fn encode<T: ::Encodable>(object: &T) -> string::String {
pub fn encode<T: ::Encodable>(object: &T) -> Result<string::String, EncoderError> {
let mut s = String::new();
{
let mut encoder = Encoder::new(&mut s);
let _ = object.encode(&mut encoder);
try!(object.encode(&mut encoder));
}
s
Ok(s)
}

impl fmt::Display for ErrorCode {
Expand Down Expand Up @@ -536,7 +536,6 @@ impl<'a> ::Encoder for Encoder<'a> {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
f(self)
}

Expand All @@ -550,10 +549,10 @@ impl<'a> ::Encoder for Encoder<'a> {
// enums are encoded as strings or objects
// Bunny => "Bunny"
// Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if cnt == 0 {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\"variant\":"));
try!(escape_str(self.writer, name));
try!(write!(self.writer, ",\"fields\":["));
Expand Down Expand Up @@ -785,7 +784,6 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
f(self)
}

Expand All @@ -797,10 +795,10 @@ impl<'a> ::Encoder for PrettyEncoder<'a> {
-> EncodeResult where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
if cnt == 0 {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); }
try!(write!(self.writer, "{{\n"));
self.curr_indent += self.indent;
try!(spaces(self.writer, self.curr_indent));
Expand Down Expand Up @@ -3537,6 +3535,24 @@ mod tests {
}
}

#[test]
fn test_hashmap_with_enum_key() {
use std::collections::HashMap;
use json;
#[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Show)]
enum Enum {
Foo,
#[allow(dead_code)]
Bar,
}
let mut map = HashMap::new();
map.insert(Enum::Foo, 0);
let result = json::encode(&map).unwrap();
assert_eq!(&result[], r#"{"Foo":0}"#);
let decoded: HashMap<Enum, _> = json::decode(result.as_slice()).unwrap();
assert_eq!(map, decoded);
}

#[test]
fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
use std::collections::HashMap;
Expand Down
2 changes: 1 addition & 1 deletion src/libsyntax/parse/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -854,7 +854,7 @@ mod test {
#[test]
fn string_to_tts_1 () {
let tts = string_to_tts("fn a (b : i32) { b; }".to_string());
assert_eq!(json::encode(&tts),
assert_eq!(json::encode(&tts).unwrap(),
"[\
{\
\"variant\":\"TtToken\",\
Expand Down
2 changes: 1 addition & 1 deletion src/test/run-pass/deriving-encodable-decodable-box.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ struct A {

fn main() {
let obj = A { foo: box [true, false] };
let s = json::encode(&obj);
let s = json::encode(&obj).unwrap();
let obj2: A = json::decode(s.as_slice()).unwrap();
assert!(obj.foo == obj2.foo);
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ fn main() {
foo: Cell::new(true),
bar: RefCell::new( A { baz: 2 } )
};
let s = json::encode(&obj);
let s = json::encode(&obj).unwrap();
let obj2: B = json::decode(s.as_slice()).unwrap();
assert!(obj.foo.get() == obj2.foo.get());
assert!(obj.bar.borrow().baz == obj2.bar.borrow().baz);
Expand Down
2 changes: 1 addition & 1 deletion src/test/run-pass/issue-14021.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ struct UnitLikeStruct;

pub fn main() {
let obj = UnitLikeStruct;
let json_str: String = json::encode(&obj);
let json_str: String = json::encode(&obj).unwrap();

let json_object = json::from_str(json_str.as_slice());
let mut decoder = json::Decoder::new(json_object.unwrap());
Expand Down