Last active
November 27, 2023 13:04
-
-
Save raminfp/e82fc862de878d94bc46ca87cf488534 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [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