Skip to content
This repository has been archived by the owner on Mar 25, 2024. It is now read-only.

Deserialization using serde_yaml seems to be failing when it involves a nested struct #395

Open
divn123 opened this issue Nov 7, 2023 · 0 comments

Comments

@divn123
Copy link

divn123 commented Nov 7, 2023

Deserialization using serde_yaml seems to be failing when it involves a nested struct like below. Is this a bug or am I missing something here?
Cargo.toml

[package]
name = "random"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde_yaml = "0.9.27"
serde = { version = "1.0.123", features = ["derive"] }

Rust code

use serde::{Deserialize, Serialize};
use std::net::SocketAddr;

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct Config<A> {
    sync: Option<bool>,
    #[serde(flatten)]
    addition: A,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct MyConfig {
    pub netconfig: Option<NetworkConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
//#[serde(tag = "type", content = "value")]
pub enum NetworkConfig {
    Ethernet(SocketAddr),
}

// #[tokio::main]
fn main() {
    let config_str = r#"
netconfig: !ethernet 192.168.2.10:1234
"#;

    let value: serde_yaml::Value = serde_yaml::from_str(config_str).unwrap();
    println!("file-to-value \n {:?}", value);
    let config: MyConfig = serde_yaml::from_value(value.clone()).unwrap();
    println!("value-to-struct\n {:?}", config);
    // This below line fails
    let config: Config<MyConfig> = serde_yaml::from_value(value).unwrap();
    println!("value-to-struct\n {:?}", config);
}

Output with error

file-to-value 
 Mapping {"netconfig": TaggedValue { tag: !ethernet, value: String("192.168.2.10:1234") }}
value-to-struct
 MyConfig { netconfig: Some(Ethernet(192.168.2.10:1234)) }
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("untagged and internally tagged enums do not support enum input")', src/main.rs:38:66
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant