You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a small use case for #[serde(flatten)] that did not work as I expected due to the intermediary presence of an Option type. Here's what I mean:
#[derive(Serialize, Deserialize)]
enum Quux {
A,
B,
C,
}
#[derive(Serialize, Deserialize)]
struct Bar {
quux: Quux,
}
#[derive(Serialize, Deserialize)]
struct Foo {
baz: i32,
#[serde(flatten)]
bar: Option<Bar>,
}
fn main() {
let f : Foo = serde_json::from_str(r#"{
"baz": 10,
"quux": "A"
}"#).unwrap(); // panics unwrapping 'Error("can only flatten structs and maps", line: 4, column: 5)'
}
I'm able to get around this problem by using my own untagged Option type.
#[derive(Serialize, Deserialize)]
enum Quux {
A,
B,
C,
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum OptBar {
Some(Bar),
None,
}
#[derive(Serialize, Deserialize)]
struct Bar {
quux: Quux,
}
#[derive(Serialize, Deserialize)]
struct Foo {
baz: i32,
#[serde(flatten)]
bar: OptBar,
}
fn main() {
let f : Foo = serde_json::from_str(r#"{
"n": 10,
"quux": "A"
}"#).unwrap(); // returns a 'Foo { n: 10, bar: Some(Bar { quux: A }) }'
}
Is there any way to get around this otherwise? Continuing to use the standard Option type allows some more straightforward checking of Foo.bar, which is quite useful. Worst case scenario I can change my data representation.
The text was updated successfully, but these errors were encountered:
I have a small use case for
#[serde(flatten)]
that did not work as I expected due to the intermediary presence of anOption
type. Here's what I mean:I'm able to get around this problem by using my own untagged
Option
type.Is there any way to get around this otherwise? Continuing to use the standard
Option
type allows some more straightforward checking ofFoo.bar
, which is quite useful. Worst case scenario I can change my data representation.The text was updated successfully, but these errors were encountered: