Created
July 16, 2024 17:30
-
-
Save evanrelf/2f19e846233bde14811137d7f502b773 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
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