jonasbb / serde_with

This crate provides custom de/serialization helpers to use in combination with serde's `with`-annotation and with the improved `serde_as`-annotation.
https://docs.rs/serde_with
Apache License 2.0
636 stars 67 forks source link

docs: include examples of using `#[serde_as(deserialize_as = .. )]` and its counterpart #766

Open chrisp60 opened 2 months ago

chrisp60 commented 2 months ago

Hello.

Thanks for making this crate. I generally use it as a convenience for simple things but had to look a little deep to determine if the #[serde_as] macro accepted deserialization and serialization specific conversion.

On the docs the field level attributes are mentioned very briefly, possibly too far down for most people to read. It may be helpful to newer users if they just see it in the example at the top of the page. Obviously, people should read the docs... but that is not always the case.

I was thinking something like below. Just a visual signpost to say "You can do this". People familiar with serde and the attributes could intuit them working. For new users to serde and Rust in general, maybe not.

Maybe there is a good place to throw no_default on there as well. Is this considered worthwhile for an addition through a PR?

#[serde_as]
#[derive(Serialize, Deserialize)]
struct Data {
    /// Serialize into number
    #[serde_as(as = "_")]
    a: u32,

    /// Serialize into String,
    /// Deserialize from Bytes or String,
    #[serde_as(
        serialize_as = "DisplayFromStr",
        deserialize_as = "BytesOrString"
    )]
    b: u32,

    /// Serialize into a map from String to String
    #[serde_as(as = "Map<DisplayFromStr, _>")]
    c: Vec<(u32, String)>,

}
jonasbb commented 2 months ago

Your idea is to extend the documentation of the serde_as macro with more examples? That sounds like a good idea. Maybe it is possible to show all kinds of variations of how the macro can be used and what kind of macros it accepts, like showcasing the crate=... argument and extra Option for the no_default.

A PR is very much welcome. My only slight concern is that this part of the documentation is currently not tested since it lives in the serde_with_macro crate.

chrisp60 commented 1 month ago

Yeah I don't think it would hurt and could possibly lead to some better user experiences. To be honest I am not entirely familiar with your second point regarding testing. I would need to do some research to see what options there are / see how other crates solve it. I guess it depends on the implementation of the macro crate as well (i.e. proc_macro vs proc_macro2).

I will try to make a PR if I have some time and see if I can look up some options for testing.