#serde #deserialization #visitor #this-or-that #multiple-type

serde-this-or-that

Custom deserialization for fields that can be specified as multiple types

8 releases

0.4.2 Feb 6, 2023
0.4.1 Feb 5, 2023
0.4.0 Apr 18, 2022
0.3.1 Apr 17, 2022
0.1.1 Apr 16, 2022

#264 in Encoding

Download history 184/week @ 2023-02-10 205/week @ 2023-02-17 361/week @ 2023-02-24 337/week @ 2023-03-03 487/week @ 2023-03-10 252/week @ 2023-03-17 443/week @ 2023-03-24 250/week @ 2023-03-31 283/week @ 2023-04-07 343/week @ 2023-04-14 207/week @ 2023-04-21 251/week @ 2023-04-28 369/week @ 2023-05-05 311/week @ 2023-05-12 272/week @ 2023-05-19 219/week @ 2023-05-26

1,259 downloads per month

MIT license

23KB
322 lines

serde-this-or-that

github crates.io docs.rs build status

Custom deserialization for fields that can be specified as multiple types.


This crate works with Cargo with a Cargo.toml like:

[dependencies]
serde-this-or-that = "0.4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

Getting started

Add some usage to your application.

Here's an example of using serde-this-or-that in code:

use serde::Deserialize;
use serde_json::from_str;
use serde_this_or_that::{as_bool, as_f64, as_u64};

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct MyStruct {
    #[serde(deserialize_with = "as_bool")]
    is_active: bool,
    #[serde(deserialize_with = "as_u64")]
    num_attempts: u64,
    #[serde(deserialize_with = "as_f64")]
    grade: f64,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let string = r#"
    {
        "isActive": "True",
        "numAttempts": "",
        "grade": "81"
    }
    "#;

    let s: MyStruct = from_str(string)?;
    println!("{s:#?}");

    assert!(s.is_active);
    assert_eq!(s.num_attempts, 0);
    assert_eq!(s.grade, 81.0);

    Ok(())
}

Exported Functions

Examples

You can check out sample usage of this crate in the examples/ folder in the project repo on GitHub.

Performance

The benchmarks suggest that implementing a custom Visitor as serde-this-or-that does, performs on average about 15x better than an approach with an untagged enum.

A separate benchmark compares performance against the serde_with crate: it indicates both crates perform about the same, assuming only DisplayFromStr is used. But when PickFirst is involved, serde-this-or-that appears to perform about 12x better in an average case.

The benchmarks live in the benches/ folder, and can be run with cargo bench.

Contributing

Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change.

Check out the Contributing section in the docs for more info.

License

This project is proudly licensed under the MIT license (LICENSE or http://opensource.org/licenses/MIT).

serde-this-or-that can be distributed according to the MIT license. Contributions will be accepted under the same license.

Authors

Dependencies

~120–380KB