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

Overview

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

You might also like...
A library for transcoding between bytes in Astro Notation Format and Native Rust data types.

Rust Astro Notation A library for transcoding between hexadecimal strings in Astro Notation Format and Native Rust data types. Usage In your Cargo.tom

An implementation of a predicative polymorphic language with bidirectional type inference and algebraic data types

Vinilla Lang Vanilla is a pure functional programming language based on System F, a classic but powerful type system. Merits Simple as it is, Vanilla

Seamless Higher-Kinded Types in Rust

Seamless Higher-Kinded Types in Rust This is actual working code: pub trait FunctorA : HKT1 { fn mapB, F: FnMut(A) - B(self, f: F) - Self::W

Algebraic structures, higher-kinded types and other category theory bad ideas

Algar Algebric structures, higher-kinded types and other category theory bad ideas. Yes, you'll have generalized functors, applicatives, monads, trave

Idiomatic Rust implementations for various Windows string types (like UNICODE_STRING)
Idiomatic Rust implementations for various Windows string types (like UNICODE_STRING)

nt-string by Colin Finck [email protected] Provides idiomatic Rust implementations for various Windows string types: NtUnicodeString (with NtUnicode

Core Temporal SDK that can be used as a base for language specific Temporal SDKs

Core SDK that can be used as a base for all other Temporal SDKs. Getting started See the Architecture doc for some high-level information. This repo u

A Matrix bot which can generate
A Matrix bot which can generate "This Week in X" like blog posts

hebbot A Matrix bot which can help to generate periodic / recurrent summary blog posts (also known as "This Week in X"). The bot was inspired by twim-

Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

Cogo is a high-performance library for programming stackful coroutines with which you can easily develop and maintain massive concurrent programs.
Cogo is a high-performance library for programming stackful coroutines with which you can easily develop and maintain massive concurrent programs.

Cogo is a high-performance library for programming stackful coroutines with which you can easily develop and maintain massive concurrent programs.

Comments
  • Provide extra functions to return Options when the input is null as Serde usually does

    Provide extra functions to return Options when the input is null as Serde usually does

    • serde-this-or-that version: 0.4
    • Rust Compiler (rustc) version: 1.66.0 (69f9c33d7 2022-12-12)
    • Operating System: Mac

    Description

    I want to get an Option when there is null value like Serde usually does. Currently, the exported functions only support types and not Options of those types. I want some extra functions like as_opt_bool, as_opt_f64, as_opt_i64, as_opt_string, as_opt_u64 which will return an Option of the respective data type.

    opened by saikrishna1-bidgely 0
Releases(v0.4.0)
  • v0.4.0(Apr 18, 2022)

    Release Notes

    Features

    • Add benchmarks to compare performance against serde_with.
    • Flatten some nested match arms into simpler if statements.
    • Update as_bool
      • Update to check for a new "truthy" string value of ON.
      • Add pattern matching to check common true/false values before converting the string to uppercase, which should make it overall more efficient.
    • serde_this_or_that is now on par - in terms of performance - with serde_with! This is truly great news.

    Full Changelog: https://github.com/rnag/serde-this-or-that/compare/v0.3.1...v0.4.0

    Source code(tar.gz)
    Source code(zip)
  • v0.3.1(Apr 17, 2022)

  • v0.3.0(Apr 17, 2022)

    Release Notes

    Breaking Changes

    • Remove dependency on the derive feature of serde
      • Add it as an optional feature named derive instead.

    Features

    • Replace utilities keyword with this-or-that, as I want crate to be searchable when someone types "this or that".
    • Update docs.

    What's Changed

    • v0.2.0: update to handle empty strings by @rnag in https://github.com/rnag/serde-this-or-that/pull/1

    New Contributors

    • @rnag made their first contribution in https://github.com/rnag/serde-this-or-that/pull/1

    Full Changelog: https://github.com/rnag/serde-this-or-that/compare/v0.2.0...v0.3.0

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Apr 17, 2022)

    Release Notes

    Features

    • Add as_string helper function, to coerce values to an owned String type.
    • Update to handle empty strings and null values in JSON (should be deserialized as "zero" values).
    • Round floats when converting to u64 or i64.
    • Similarly, handle floating-point values in strings when converting to u64 or i64.
    • Refactor to use Result<Self::Value, E> everywhere, instead of Result<T, E>.
    • Rename de.rs -> de_impl.rs to avoid name conflicts.
    • Add example as_string.rs
    • Update examples/
    • Update docs

    Full Changelog: https://github.com/rnag/serde-this-or-that/compare/v0.1.1...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.1(Apr 16, 2022)

  • v0.1.0(Apr 16, 2022)

Owner
Ritvik Nag
Python / Typescript developer, currently learning Rust 🦀
Ritvik Nag
Rust library for concurrent data access, using memory-mapped files, zero-copy deserialization, and wait-free synchronization.

mmap-sync mmap-sync is a Rust crate designed to manage high-performance, concurrent data access between a single writer process and multiple reader pr

Cloudflare 97 Jun 26, 2023
probe-run is a custom Cargo runner that transparently runs Rust firmware on an embedded device

probe-run Runs embedded programs just like native ones probe-run is a custom Cargo runner that transparently runs Rust firmware on an embedded device.

Knurling 483 Jan 7, 2023
Custom formatting for Rust.

custom-format This crate extends the standard formatting syntax with custom format specifiers, by providing custom formatting macros. It uses : (a spa

null 6 Dec 14, 2022
proc-macro to help with using surrealdb's custom functions

SurrealDB Functions This is a proc-macro crate that given a path to a .surql file or a folder of .surql files, will parse DEFINE FUNCTION fn::s inside

Aly 5 Jul 30, 2023
Rust language from simple to deep, and then to strengthen learning in multiple module

Rust Library This project is used to learn rust language from simple to deep, and then to strengthen learning in multiple module. It is used to help n

Summer 1 Sep 19, 2022
A tool and library to losslessly join multiple .mp4 files shot with same camera and settings

mp4-merge A tool and library to losslessly join multiple .mp4 files shot with same camera and settings. This is useful to merge multiple files that ar

Gyroflow 7 Jan 2, 2023
A minimal boilerplate for Astro / Vite with the Nannou creative framework (Rust → WASM). Supports multiple sketches + hot-reload.

Astro x Nannou Starter astro-nannou-demo-1c.mov ?? Try it online! # 0a. Rust language tools open https://www.rust-lang.org/tools/install # 0b. wasm-p

Julian Cataldo 4 Jan 4, 2023
Repo for apps for the Pocket RISC-V core for Analogue Pocket/OpenFPGA. Multiple branches.

This is a repo meant to host Rust programs for agg23's Pocket RISC-V platform. While Rust can be built out of the openfpga-litex repo directly, this r

null 3 Dec 12, 2023
A typemap for a set of known types optionally without heap allocation, and supporting iterating by traits

fixed_typemap docs.rs GitHub Sponsors Implements typemaps that support a lot of extra funcctionality using procedural macros. docs.rs has a lot more t

Austin Hicks 2 Dec 27, 2021