Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Incompatiblity issue with enum variant externally tagged #19

Open
loganmzz opened this issue Feb 18, 2025 · 0 comments
Open

[Bug] Incompatiblity issue with enum variant externally tagged #19

loganmzz opened this issue Feb 18, 2025 · 0 comments

Comments

@loganmzz
Copy link

Serde relies by default to externally tagged for enum variants. For example:

#[derive(Debug,Deserialize,PartialEq,Serialize)]
enum StringOrNumber {
    String(String),
    Number(u64),
}

#[test]
fn to_json() {
    assert_eq!(
        r#"
{
  "Number": 42
}
"#.trim(),
        serde_json::to_string_pretty(&StringOrNumber::Number(42)).unwrap(),
    );
}

#[test]
fn from_json() {
    assert_eq!(
        StringOrNumber::Number(42),
        serde_json::from_str(r#"
{
  "Number": 42
}
"#).unwrap(),
    );
}

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c2ca0468b627ea6491eab5c122273ca3


However, you can't parse it from YAML-impl while:

  • JSON input is compatible with YAML
  • The same model/mapping/framework is in use.

Demonstration:

#[derive(Debug,Deserialize,PartialEq,Serialize)]
enum StringOrNumber {
    String(String),
    Number(u64),
}

#[test]
fn to_yaml() {
    assert_eq!(
        r#"
Number: 42
"#.trim_start(),
        serde_yaml::to_string(&StringOrNumber::Number(42)).unwrap(),
    );
}

#[test]
fn from_json() {
    assert_eq!(
        StringOrNumber::Number(42),
        serde_yaml::from_str(r#"
{
  "Number": 42
}
"#).unwrap(),
    );
}

#[test]
fn from_yaml() {
    assert_eq!(
        StringOrNumber::Number(42),
        serde_yaml::from_str(r#"
Number: 42
"#).unwrap(),
    );
}

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e23c1abf4cb53373edb08862b69d7d4e


I have also initialized a crate to reference any other issues: https://github.com/loganmzz/serde-yaml-ng-compatibility-issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant