Capture fields in serde when flattening multiple struct members

I am currently trying to find a way to have serde capture additional fields inside a struct when having an enum field in the struct also flattened. My main problem is that fields that are already part of a flattened struct are still added to the HashMap that should only contain the additional fields.

This is a (somewhat) minimal example:

use std::collections::HashMap;
use serde::Deserialize;
use serde_json::Value;

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Type {
    Record {
        name: String,
        fields: Vec<Value>,

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub struct Schema {
    pub ty: Type,
    pub logical_type: Option<String>,
    pub values: HashMap<String, Value>,

fn main() {
    let s: Schema = serde_json::from_str(r#"{
        "name": "foo",
        "logicalType": "bar",
        "fields": []
    println!("s = {:#?}", s);

In the example above you can see that this works for the fields inside the Schema struct but still adds the fields that should already be captured inside Type.

One way would of course be to replicate some of the logic for map deserialization in a custom deserializer, another one would be to introduce an intermediate struct and converting. Is there an easier way to achieve something like this?

I cannot provide any help but I am facing the exact same issue :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.