Skip to content

Instantly share code, notes, and snippets.

@clbarnes
Created August 22, 2025 22:44
Show Gist options
  • Select an option

  • Save clbarnes/9fa6198ec94bfab451600314baecf40e to your computer and use it in GitHub Desktop.

Select an option

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
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