google / serde_json5

Apache License 2.0
12 stars 9 forks source link

enum variant deserialization doesn't match serde_json #10

Open woody77 opened 3 months ago

woody77 commented 3 months ago

serde_json5 will deserialize variant_name: {} into a unit-type variant.

An example

        #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
        #[serde(rename_all="snake_case")]
        enum SomeEnum{
            VariantA(String),
            VariantB,
        }

        #[derive(Debug, Clone, Deserialize, Serialize)]
        struct SomeStruct {
            some_enum: SomeEnum
        }

        // This (correctly) passes.
        let json5 = r#"{some_enum: "variant_b" }"#;
        let parsed: SomeStruct = serde_json5::from_str(json5).unwrap();
        assert_eq!(parsed.some_enum, SomeEnum::VariantB);

        // This (incorrectly) passes
        let json5 = r#"{some_enum: { "variant_b": {} }}"#;
        let parsed: SomeStruct = serde_json5::from_str(json5).unwrap();
        assert_eq!(parsed.some_enum, SomeEnum::VariantB);

In the above example, if the json5 is bounced through a serde_json::Value, and that is deserialized into a struct, an error is thrown:

let json5 = r#"{some_enum: { "variant_b": {} }}"#;
let value: serde_json::Value = serde_json5::from_str(json5).unwrap();
let parsed: SomeStruct = serde_json::from_value(value).unwrap();  // fails with an error
assert_eq!(parsed.some_enum, SomeEnum::VariantB);

The error is: invalid type: map, expected unit