serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
9.16k stars 774 forks source link

Custom serde_json::Value deserialization? #2085

Closed lquerel closed 2 years ago

lquerel commented 3 years ago

I'd like to apply a normalization function on the field names when deserializing to serde_json::Value.

let field_normalizer = |name: &str| {
            return name.to_lowercase().replace("#", "_");
};

let value: Value = serde_json::from_str_with_custom_normalizer(r#"{"Field_1": 1, "Field#2": 2}"#, field_normalizer)?;
dbg(&value);

The value displayed by the dbg macro should be:

[main.rs:10] &value = Object({
    "field_2": Number(
        2,
    ),
    "field_1": Number(
        1,
    ),
})

I'm well aware of the possible name collision after normalization but I have a mechanism to deal with that.

How can I implement a such custom generic deserialization without creating a modified copy of a Value?

dtolnay commented 2 years ago

Please take this question to one of the resources listed in https://github.com/serde-rs/serde/tree/v1.0.135#getting-help. Sorry that no one was able to provide guidance here.