Skip to content
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

Parametrize serde_json::value::Serializer with Strategy to serialize values #1028

Closed
mineichen opened this issue Jun 19, 2023 · 1 comment
Closed

Comments

@mineichen
Copy link

mineichen commented Jun 19, 2023

Feature request:

Currently, the serde_json::value::Serializer uses to_value() at various points. It would be very convenient to allow configuring this via Generics. Today, this Serializer cannot collect metadata or have special logic, which is applied on all nesting-levels. This pseudo code shows a solution to overcome this limitation:

pub trait SerializeToValue {
   fn serialize_value<S: Serialize>(&mut self, key: &str, item: S) -> Result<serde_json::Value, serde_json::error::Error>;
}

#[derive(Default)]
struct DefaultSerializeToValue;
impl SerializeToValue for DefaultSerializeToValue  {
   fn serialize_value<S: Serialize>(&mut self, key: &str, item: S) -> Result<serde_json::Value, serde_json::error::Error> {
      to_value(item)
   }
}

// In the next major version, this could be added:
// type Serializer = GenericSerializer<DefaultSerializeToValue>;
struct GenericSerializer<T=DefaultToValue> {
   strategy: T
}

Instead of to_value, we could then use self.strategy.serialize_value (e.g. in serialize_newtype_variant). The runtime performance should not change, but there might be some build-time regressions.

As you can see, the above solution doesn't work without breaking changes. Would you consider to mark Serializer deprecated and add a GenericSerializer<T>? For now, the serde_json::value::Serializer and serde_json::value::GenericSerializer could be generated with a macro to avoid Code-Duplication. An alternative would be to ship this Serializer in a separate crate and duplicate the serde_json::value::Serializer code.

@dtolnay
Copy link
Member

dtolnay commented Jun 19, 2023

I would prefer not to build this into this crate, so you would need to put it in a different crate.

@dtolnay dtolnay closed this as completed Jun 19, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants