Skip to content

Commit

Permalink
feat(json): added field aliases, were needed
Browse files Browse the repository at this point in the history
This makes sure our fields can properly be decoded.
  • Loading branch information
Byron committed Mar 20, 2015
1 parent b9a81a9 commit 9f719dd
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/mako/lib.rs.mako
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ ${lib.docs(c)}
// unused imports in fully featured APIs. Same with unused_mut ... .
#![allow(unused_imports, unused_mut)]
// Required for serde annotations
#![feature(custom_derive, plugin)]
#![feature(custom_derive, custom_attribute, plugin)]
#![plugin(serde_macros)]

extern crate hyper;
Expand Down
3 changes: 3 additions & 0 deletions src/mako/lib/schema.mako
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
${struct} {
% for pn, p in properties.iteritems():
${p.get('description', 'no description provided') | rust_doc_comment, indent_all_but_first_by(1)}
% if pn != mangle_ident(pn):
#[serde(alias="${pn}")]
% endif
pub ${mangle_ident(pn)}: ${to_rust_type(schemas, s.id, pn, p)},
% endfor
}
Expand Down
39 changes: 37 additions & 2 deletions src/rust/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![feature(core,io,old_path, custom_derive, plugin)]
#![allow(dead_code, deprecated, unused_features)]
#![feature(core,io,old_path, custom_derive, custom_attribute, plugin)]
#![allow(dead_code, deprecated, unused_features, unused_variables, unused_imports)]
//! library with code shared by all generated implementations
#![plugin(serde_macros)]
extern crate hyper;
Expand All @@ -20,6 +20,8 @@ mod tests {
use std::default::Default;
use std::old_path::BytesContainer;

use serde::json;

const EXPECTED: &'static str =
"\r\n--MDuXWGyeE33QFXGchb2VFWc4Z7945d\r\n\
Content-Length: 50\r\n\
Expand Down Expand Up @@ -77,4 +79,37 @@ bar\r\n\
// See above: headers are unordered
// assert_eq!(v.container_as_str().unwrap(), EXPECTED);
}

#[test]
fn serde() {
#[derive(Default, Serialize, Deserialize)]
struct Foo {
opt: Option<String>,
req: u32,
opt_vec: Option<Vec<String>>,
vec: Vec<String>,
}

let f: Foo = Default::default();
json::to_string(&f).unwrap(); // should work

let j = "{\"opt\":null,\"req\":0,\"vec\":[]}";
let f: Foo = json::from_str(j).unwrap();

// This fails, unless 'vec' is optional
// let j = "{\"opt\":null,\"req\":0}";
// let f: Foo = json::from_str(j).unwrap();

#[derive(Default, Serialize, Deserialize)]
struct Bar {
#[serde(alias="snooSnoo")]
snoo_snoo: String
}
json::to_string(&<Bar as Default>::default()).unwrap();


let j = "{\"snooSnoo\":\"foo\"}";
let b: Bar = json::from_str(&j).unwrap();
assert_eq!(b.snoo_snoo, "foo");
}
}

0 comments on commit 9f719dd

Please sign in to comment.