feat(json): added field aliases, were needed

This makes sure our fields can properly be decoded.
This commit is contained in:
Sebastian Thiel
2015-03-20 14:16:06 +01:00
parent b9a81a900e
commit 9f719dd928
3 changed files with 41 additions and 3 deletions

View File

@@ -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;

View File

@@ -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
}

View File

@@ -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;
@@ -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\
@@ -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");
}
}