ebarnard / rust-plist

A rusty plist parser.
MIT License
71 stars 42 forks source link

Serializing/deserializing an array of fieldless enum variants #53

Closed steven-joruk closed 4 years ago

steven-joruk commented 4 years ago

Hello, I'm not sure if this requires a feature request, or of I'm just misusing the library. How would you achieve this serialization?

#[derive(Serialize)]
enum Thing {
    #[serde(rename = "a")]
    A,

    #[serde(rename = "b")]
    B,

    #[serde(rename = "c")]
    C
};

struct Container { things: Vec<Thing> }

Expected XML format:

...
   <key>things</key>
    <array>
        <string>a</string>
        <string>c</string>
    </array>
...

Actual:

        <key>things</key>
        <array>
                <dict>
                        <key>a</key>
                        <string></string>
                </dict>
                <dict>
                        <key>c</key>
                        <string></string>
                </dict>
        </array>

Thanks

ebarnard commented 4 years ago

I'm not sure there's a built-in way to do this at present.

The simplest way, assuming you just have one or two enums like this, would be to impl TryFrom<String> and Into<&'static str> for each enum, and then put #[serde(try_from = "String")] and #[serde(into = "&'static str")] attributes on the enum (you might be able to use &str instead of String).

This certainly is a feature that could directly be supported by this library, or ideally by serde itself.

steven-joruk commented 4 years ago

That solution is good for me, thanks. I've used the method in the original post when using serde_json, but I haven't looked at how it's implemented.

ebarnard commented 4 years ago

FYI this seems to be the change that enables this behavior in serde_json: https://github.com/serde-rs/json/pull/76.