samscott89 / serde_qs

Serde support for querystring-style strings
Apache License 2.0
193 stars 68 forks source link

Serialization round-trip fails with empty Vec #78

Open dfaust opened 1 year ago

dfaust commented 1 year ago

When serializing a struct containing an empty Vec, the Vec is completely dropped. But when de-serializing the struct, the Vec is required. This breaks the serialization round-trip.

My expectation is that the de-serializing should work, even if the Vec is not present.

Here is an example:

#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Data {
    values: Vec<String>,
}

#[test]
fn serialization_roundtrip() {
    let data = Data { values: Vec::new() };

    let serialized = serde_qs::to_string(&data).unwrap();

    dbg!(&serialized);

    let deserialized = serde_qs::from_str::<Data>(&serialized).unwrap();

    assert_eq!(deserialized, data);
}
samscott89 commented 1 year ago

Hey @dfaust!

Thanks for opening an issue. You raise an interesting problem. I'm struggling to come up with a way that we could solve this on the serde_qs side. I don't think there's any way for us to represent an empty vector.

One thing you could maybe do as a workaround it:

#[test]
fn serialization_roundtrip() {
    #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
    struct Data {
        #[serde(default)] // <<<<< use this
        values: Vec<String>,
    }

    let data = Data { values: Vec::new() };
    let serialized = serde_qs::to_string(&data).unwrap();

    dbg!(&serialized);
    let deserialized = serde_qs::from_str::<Data>(&serialized).unwrap();
    assert_eq!(deserialized, data);
}

Do you think that would be possible?

dfaust commented 1 year ago

Thanks @samscott89 for the quick reply!

Do you think that would be possible?

Sure. That's an easy enough work-around. :+1:

I still hope that you can find a solution though, since this behavior is quite surprising.

Anyway, I still love your crate. Being able to serialize Vecs as URLs is fantastic!

gitmalong commented 8 months ago

Issue also occurs with an empty HashSet