Skip to content

Instantly share code, notes, and snippets.

@evanrelf
Created July 16, 2024 17:30
Show Gist options
  • Save evanrelf/2f19e846233bde14811137d7f502b773 to your computer and use it in GitHub Desktop.
Save evanrelf/2f19e846233bde14811137d7f502b773 to your computer and use it in GitHub Desktop.
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json;
#[derive(Debug, Serialize, Deserialize)]
struct Foo(String);
#[derive(Debug, Serialize, Deserialize)]
struct Bar(String);
fn foo_ser<S>(value: &Foo, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Foo(format!("{}!!!", value.0)).serialize(serializer)
}
fn foo_de<'de, D>(deserializer: D) -> Result<Foo, D::Error>
where
D: Deserializer<'de>,
{
let value = Foo::deserialize(deserializer)?;
Ok(Foo(String::from(
value.0.strip_suffix("!!!").unwrap_or(&value.0),
)))
}
#[derive(Debug, Serialize, Deserialize)]
struct Thing {
#[serde(serialize_with = "foo_ser", deserialize_with = "foo_de")]
foo: Foo,
bar: Bar,
}
fn main() {
let input = Thing {
foo: Foo(String::from("foo")),
bar: Bar(String::from("bar")),
};
let json = serde_json::to_string(&input).unwrap();
let output: Thing = serde_json::from_str(&json).unwrap();
println!(" {input:?}\n-> {json}\n-> {output:?}");
}
// Thing { foo: Foo("foo"), bar: Bar("bar") }
// -> {"foo":"foo!!!","bar":"bar"}
// -> Thing { foo: Foo("foo"), bar: Bar("bar") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment