Serde: Support deserializing a flattened internally tagged enum

Created on 23 Mar 2018  路  1Comment  路  Source: serde-rs/serde

This would be valuable to support if possible. Serialization already works but deserialization does not.

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

#[derive(Serialize, Deserialize, Debug)]
struct Data {
    id: i32,
    #[serde(flatten)]
    payload: Enum,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
enum Enum {
    A(A),
    B(B),
}

#[derive(Serialize, Deserialize, Debug)]
struct A {
    field_a: i32,
}

#[derive(Serialize, Deserialize, Debug)]
struct B {
    field_b: i32,
}

fn main() {
    let data = Data {
        id: 0,
        payload: Enum::A(A { field_a: 0 }),
    };

    let j = serde_json::to_string(&data).unwrap();
    println!("{}", j);

    println!("{}", serde_json::from_str::<Data>(&j).unwrap_err());
}
{"id":0,"type":"A","field_a":0}
can only flatten structs and maps at line 1 column 31
enhancement

Most helpful comment

@mammothbane @Nemikolh @weiwei-lin @georgemarshall @PlasmaPower @jplatte
this is now supported in 1.0.46!

>All comments

@mammothbane @Nemikolh @weiwei-lin @georgemarshall @PlasmaPower @jplatte
this is now supported in 1.0.46!

Was this page helpful?
0 / 5 - 0 ratings