-
Notifications
You must be signed in to change notification settings - Fork 72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Serialize struct with additional root element #340
Comments
#![feature(adt_const_params)]
#[derive(Copy, Clone, Debug, Default)]
pub struct Layer<const FIELD: &'static str, T: ?Sized>(T);
impl<const FIELD: &'static str, T, U> SerializeAs<T> for Layer<FIELD, U>
where
U: SerializeAs<T>,
T: ?Sized,
U: ?Sized,
{
fn serialize_as<S>(source: &T, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
use serde::ser::SerializeStruct;
let mut ser_struct = serializer.serialize_struct("Layer", 1)?;
ser_struct.serialize_field(FIELD, &ser::SerializeAsWrap::<T, U>::new(source))?;
ser_struct.end()
}
}
// Can be used like this
#[serde_as]
#[derive(Serialize)]
struct Data {
i: i32,
#[serde_as(as = r#"Layer<"extra", Layer<"foobar", Layer<"really_another_one", DisplayFromStr>>>"#)]
b: bool,
}
// or like
serde_json::to_string(&Layer::<"root">(&data)) https://github.com/dtolnay/monostate contains a solution to encode |
Would like to see this feature implemented still |
I would like to see this implemented too, that is why the issue is still open. But nothing has changed so far. serde will not implement it. A proper alternative would require forking |
This seems related to the general issue of parameterize SerializeAs structs. For example, for a database I have an |
Sometimes structs/enums need an additional root element. This can be done with a single element enum like so:
A better solution would be a macro which adds the root element without requiring changing the struct.
Prior art
The text was updated successfully, but these errors were encountered: