Coder Social home page Coder Social logo

Comments (3)

nox avatar nox commented on July 28, 2024 5

The solution is to just use serde_json yourself for whichever keys you want

from serde_urlencoded.

rnag avatar rnag commented on July 28, 2024

Update: It looks like currently serde_url_encoded might not support nested struct or also HashMap (and other map-like) types. If anyone is curious, my current workaround is to implement a custom Serializer for the main struct, defined as follows:

use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};

impl<'a> Serialize for AuditLogParams<'a> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut s = if let Some(ref filters) = self.filters {
            let mut s = serializer.serialize_struct("AuditLogParams", 3)?;
            s.serialize_field("filters", &serde_json::to_string(filters).unwrap())?;
            s
        } else {
            serializer.serialize_struct("AuditLogParams", 2)?
        };
        s.serialize_field("page", &self.page)?;
        s.serialize_field("per_page", &self.per_page)?;

        s.end()
    }
}

For a more generic approach, one could also use serialize_with along with a helper function defined as follows:

/// Helper function to serialize a `struct` as a JSON string, to be used with
/// the [`serialize_with`] attribute.
///
/// # Example
/// ```rust
/// #[derive(Debug, Serialize, Deserialize)]
/// struct MyStruct {
///     #[serde(serialize_with = "to_json_string")]
///     #[serde(skip_serializing_if = "Option::is_none")]
///     my_field: Option<Inner>,
/// }
///
/// struct Inner;
/// ```
///
/// [`serialize_with`]: https://serde.rs/field-attrs.html#serialize_with
fn to_json_string<S, T>(t: &T, s: S) -> std::result::Result<S::Ok, S::Error>
where
    S: Serializer,
    T: Serialize,
{
    s.serialize_str(&serde_json::to_string(t).unwrap())
}

Then my tests in the crate now look like this:

#[cfg(test)]
mod tests {
    use super::*;
    use serde_urlencoded::to_string;

    #[test]
    fn test_serialize_filters_as_url_encoded_params() -> Result<()> {
        sensible_env_logger::safe_init!();

        let filters = FilterParams {
            start_time: "2020-08-24T17:03:00Z",
            end_time: "",
        };

        let params = AuditLogParams::from(filters);

        let result = to_string(params)?;
        trace!(result); // "filters=%7B%22start_time%22%3A%222020-08-24T17%3A03%3A00Z%22%7D&page=1&per_page=1000"

        // result contains `start_time` but *not* the `end_time`
        assert!(result.contains("start_time"));
        assert!(!result.contains("end_time"));

        Ok(())
    }
}

from serde_urlencoded.

rnag avatar rnag commented on July 28, 2024

Hi @nox , curious if any update was implemented as part of this issue? I did put together a workaround which appears to work for now, however I think it would be great if serde_urlencoded supported such a use case (nested structs and maps) out of the box. I think it would be pretty unambiguous to implement as well - essentially just using serde_json library to serialize the nested values.

from serde_urlencoded.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.