serde_qs icon indicating copy to clipboard operation
serde_qs copied to clipboard

Serialization round-trip fails with empty Vec

Open dfaust opened this issue 1 year ago • 3 comments

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);
}

dfaust avatar Feb 28 '23 20:02 dfaust

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?

samscott89 avatar Mar 02 '23 05:03 samscott89

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!

dfaust avatar Mar 02 '23 20:03 dfaust

Issue also occurs with an empty HashSet

gitmalong avatar Feb 18 '24 19:02 gitmalong