Skip to content

Instantly share code, notes, and snippets.

@softprops
Created December 12, 2017 04:52
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 softprops/a212d247be9bf015038e4b7dfbdc888b to your computer and use it in GitHub Desktop.
Save softprops/a212d247be9bf015038e4b7dfbdc888b to your computer and use it in GitHub Desktop.
#[macro_use]
extern crate serde;
extern crate serde_json;
use serde::Serializer;
fn comma_delim<S>(
x: &Option<Vec<String>>,
ser: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *x {
Some(ref elems) => {
ser.serialize_str(
elems.join(",").as_ref(),
)
}
_ => ser.serialize_none(),
}
}
#[derive(Serialize, Debug)]
struct Foo {
#[serde(serialize_with="comma_delim")]
pub bar: Option<Vec<String>>
}
fn main() {
println!("{:?}", serde_json::to_string(&Foo { bar: Some(vec!["foo".to_string(), "bar".to_string()]) }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment