Created
August 22, 2025 22:44
-
-
Save clbarnes/9fa6198ec94bfab451600314baecf40e to your computer and use it in GitHub Desktop.
Use serde JSON to decompose a serialised flat object into a tuple of different structs
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::de::DeserializeOwned; | |
| trait JsonDeserializable { | |
| fn deser<T: DeserializeOwned>(self) -> serde_json::Result<T>; | |
| } | |
| impl JsonDeserializable for serde_json::Value { | |
| fn deser<T: DeserializeOwned>(self) -> serde_json::Result<T> { | |
| serde_json::from_value(self) | |
| } | |
| } | |
| impl JsonDeserializable for &[u8] { | |
| fn deser<T: DeserializeOwned>(self) -> serde_json::Result<T> { | |
| serde_json::from_slice(self) | |
| } | |
| } | |
| impl JsonDeserializable for &str { | |
| fn deser<T: DeserializeOwned>(self) -> serde_json::Result<T> { | |
| serde_json::from_str(self) | |
| } | |
| } | |
| macro_rules! cascade_deser { | |
| ($value:expr, $($y:ident),+) => {{ | |
| #[derive(serde::Deserialize)] | |
| struct Inner { | |
| $( | |
| #[serde(flatten)] | |
| $y: $y, | |
| )+ | |
| #[serde(flatten)] | |
| _other: serde_json::Value, | |
| } | |
| JsonDeserializable::deser::<Inner>($value).map(|inner| { | |
| ( | |
| $( | |
| inner.$y, | |
| )+ | |
| inner._other | |
| ) | |
| }) | |
| }}; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment