Comments (3)
The solution is to just use serde_json yourself for whichever keys you want
from serde_urlencoded.
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.
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)
- Support serializing bytes HOT 1
- Fail to properly deserialize sequences HOT 3
- Serialize serde_json::Value::Object contains Null/None get error Custom("unsupported value")
- Missing tags for releases 0.7.0 and 0.7.1
- Reconsider depending on URL HOT 3
- Consider switching from dtoa to ryu HOT 1
- Arrays support HOT 3
- Clarification request: What kind of structs can be deserialized to by this crate? HOT 3
- Release new version HOT 1
- Example for chrono::NaiveDateTime in qs HOT 5
- Please publish a new version HOT 4
- Support sequence-like values in a key-value map HOT 3
- Data did not match any variant of untagged enum
- Could we get more context on the errors? HOT 1
- Getting help section in the README is out-of-date
- Fresh serde_urlencoded v0.7.0 warning: use of deprecated associated function
- Yank serde_urlencoded 0.7.0 HOT 1
- [DISC] Percent decoding HOT 5
- Support deserializing `u128`/`i128`
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from serde_urlencoded.