Serialize a vec with serde_urlencoded

Hi,

I try do send an http request with the reqwest crate. This request need query parameters so I build them with a struct. Reqwest serialize the struct with the help of serde_urlencoded. But this serializer doesn’t support Vectors. Is there a way to tell serde to use a custom function to serialize a Vec ?

#[derive(Debug, Serialize)]
pub enum Direction {
    Ascending,
    Descending,
}

#[derive(Debug, Serialize)]
pub struct Query {
  pub foo: Option<bool>,
  pub bar: Vec<Direction>,
}

fn build_request() -> RequestBuilder {
  let query = Query {
    foo: Some(true),
    bar: vec![Direction::Ascending, Direction::Descending],
  };

  Client::builder().build()?
    .get("/baz")
    .query(&query)
}

query struct should be serialized to "?foo=true&bar=Ascending,Descending

Just add #[serde(serialize_with="func_name")] to bar field and you will achieve what you want, see: Field attributes · Serde

Thanks for pointing me to the doc.

I've implemented a serializer function

fn func_name<S>(vec: &Vec<Direction>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut seq = serializer.serialize_seq(Some(vec.len()))?;

    for element in vec {
        seq.serialize_element(element)?;
    }

    seq.end()
}

but when I build the request I still have the error of "unsupported value"

RequestBuilder { client: Client, request: Err(reqwest::Error { kind: Builder, source: Custom("unsupported value") }) }

serde_urlencoded won't let you use serializer.serialize_seq(). You'll have to do something like the following to create a &str:

fn func_name<S>(vec: &Vec<Direction>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_str(vec.iter().map(ToString::to_string).collect::<Vec<String>>().join(",").as_str())
}