Custom serde deserializer issues with supporting serde(flatten)

⚓ Rust    📅 2025-12-17    👤 surdeus    👁️ 1      

surdeus

I have written a custom deserializer which works for what I need, but I was messing about with adding #[serde(flatten)] to a struct and noticed it no longer worked. I tracked the issue down to serde calling deserialize_any instead of one of the type hinted function e.g. deserialize_i32. Since my format is not self describing I need the type hints from serde to correctly deserialize each field.

Does flatten not support formats that arent self descriptive?

Is there away around this?

Do I need to explictly tell serde that deserialize_any does not work? I was forced to implement the function and currently just return an error. I have also tried returning visitor.visit_none()

thank you in advance!

For example for the following structs my calls look something like

/*
deserialize_map
  next_key_seed
    deserialize_str // "x"
  next_value_seed
    deserialize_i32 // serde "correctly" calls a type hinted function
  next_key_seed
    deserialize_str // "y"
  next_value_seed
    deserialize_any  // <== here is the issue I want deserialize_i32
*/

#[derive(Deserialize)]
struct params {
  x: i32,
  #[serde(flatten)]
  flat: Flatten,
}

#[derive(Deserialize)]
struct Flatten {
  y: i32,
  z: i32,
}

2 posts - 2 participants

Read full topic

🏷️ Rust_feed