Skip to content

Instantly share code, notes, and snippets.

@jlgerber
Last active June 18, 2016 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlgerber/bf9c768c553acca6a8535cc609654796 to your computer and use it in GitHub Desktop.
Save jlgerber/bf9c768c553acca6a8535cc609654796 to your computer and use it in GitHub Desktop.
#![feature(custom_derive, plugin)]
#![feature(custom_attribute)]
#![plugin(serde_macros)]
extern crate serde;
extern crate serde_json;
use serde::ser::Serializer;
fn main() {
println!("Hello, world!");
}
trait MySerialization {
fn serialize_with<S: Serializer>(&self, serializer: &mut S) -> Result<(), S::Error>;
}
pub type Id = u64;
pub type Ids = Vec<Id>;
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub enum Object {
Id(Id),
Ids(Ids),
}
// when Object follows other member, an additional comma is
// inserted into the serialization, if the object is a vector.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct ObjWrap {
pub relation: String,
#[serde(serialize_with="MySerialization::serialize_with")]
pub values: Object,
}
// when the object comes first, serialization works as expected
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct ObjWrapGood {
#[serde(serialize_with="MySerialization::serialize_with")]
pub values: Object,
pub relation: String,
}
impl MySerialization for Object {
fn serialize_with<S: Serializer>(&self, serializer: &mut S) -> Result<(), S::Error> {
match self {
&Object::Id(i) => serializer.serialize_u64(i),
&Object::Ids(ref vi) => serializer.serialize_seq_elt(vi),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn objwrap_id_to_json() {
let obj = ObjWrap{relation:String::from("foo"), values:Object::Id(333)};
let result = serde_json::to_string(&obj).unwrap();
let expectation = "{\"relation\":\"foo\",\"values\":333}";
assert_eq!(result, expectation);
}
#[test]
fn objwrap_ids_to_json() {
let obj = ObjWrap{relation:String::from("foo"), values:Object::Ids(vec![333,444])};
let result = serde_json::to_string(&obj).unwrap();
let expectation = "{\"relation\":\"foo\",\"values\":[333,444]}";
assert_eq!(result, expectation);
}
// this works as object comes first.
#[test]
fn objwrap_good_id_to_json() {
let obj = ObjWrapGood{relation:String::from("foo"), values:Object::Id(444)};
let result = serde_json::to_string(&obj).unwrap();
let expectation = "{\"values\":444,\"relation\":\"foo\"}";
assert_eq!(result, expectation);
}
#[test]
fn objwrap_good_ids_to_json() {
let obj = ObjWrapGood{relation:String::from("foo"), values:Object::Ids(vec![333,444])};
let result = serde_json::to_string(&obj).unwrap();
let expectation = "{\"values\":[333,444],\"relation\":\"foo\"}";
assert_eq!(result, expectation);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment