Skip to content

Instantly share code, notes, and snippets.

@raminfp
Last active November 27, 2023 13:04
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 raminfp/e82fc862de878d94bc46ca87cf488534 to your computer and use it in GitHub Desktop.
Save raminfp/e82fc862de878d94bc46ca87cf488534 to your computer and use it in GitHub Desktop.
// [dependencies]
// serde = { version = "1.0.193", features = [] }
// serde_json = { version = "1.0.108", features = [] }
use serde::{Serialize, Serializer};
use std::fmt;
struct Name {
first_name: String,
last_name: String,
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.first_name, self.last_name)
}
}
// Implement Serialize to customize JSON serialization
// Use serializer.collect_str() to append to buffer directly
impl Serialize for Name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(&self)
}
}
fn serialize_names(names: &[Name]) -> serde_json::Result<String> {
serde_json::to_string(names)
}
fn main() {
let names = vec![
Name {
first_name: "John".to_string(),
last_name: "Doe".to_string(),
},
Name {
first_name: "Jane".to_string(),
last_name: "Doe".to_string(),
}
];
let json = serialize_names(&names).unwrap();
println!("{}", json);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment