All Projects → jonasbb → serde_with

jonasbb / serde_with

Licence: Apache-2.0, MIT licenses found Licenses found Apache-2.0 LICENSE-APACHE MIT LICENSE-MIT
This crate provides custom de/serialization helpers to use in combination with serde's `with`-annotation and with the improved `serde_as`-annotation.

Programming Languages

rust
11053 projects
Dockerfile
14818 projects

Projects that are alternatives of or similar to serde with

Typical
Typical: Fast, simple, & correct data-validation using Python 3 typing.
Stars: ✭ 111 (-71.68%)
Mutual labels:  annotations, serde
fitparse-rs
Rust library to parse FIT formatted files
Stars: ✭ 20 (-94.9%)
Mutual labels:  crates, serde
data-encoding
Efficient and customizable data-encoding functions in Rust
Stars: ✭ 92 (-76.53%)
Mutual labels:  hex, base64
Accord
Data validation library for Rust
Stars: ✭ 72 (-81.63%)
Mutual labels:  crates, serde
utils.js
👷 🔧 zero dependencies vanilla JavaScript utils.
Stars: ✭ 14 (-96.43%)
Mutual labels:  hex, base64
Tints And Shades
🌈 Display tints and shades of a given hex color in 10% increments.
Stars: ✭ 228 (-41.84%)
Mutual labels:  hex
controller-logger
AOP based API logging for Spring Boot
Stars: ✭ 57 (-85.46%)
Mutual labels:  annotations
Elixir Json
Native JSON library for Elixir
Stars: ✭ 216 (-44.9%)
Mutual labels:  hex
Number
ActionView::Helpers::NumberHelper for Elixir
Stars: ✭ 186 (-52.55%)
Mutual labels:  hex
hext
Markup language and tool for generating binary files
Stars: ✭ 23 (-94.13%)
Mutual labels:  hex
cns
Search through rust crates without leaving the terminal
Stars: ✭ 23 (-94.13%)
Mutual labels:  crates
svg64
Convert SVG to base64 in Node and the browser
Stars: ✭ 24 (-93.88%)
Mutual labels:  base64
Dynamiccolor
Yet another extension to manipulate colors easily in Swift and SwiftUI
Stars: ✭ 2,677 (+582.91%)
Mutual labels:  hex
simple-commands
An (even more) simplified and intuitive command framework for Spigot.
Stars: ✭ 14 (-96.43%)
Mutual labels:  annotations
Ecto mnesia
Ecto adapter for Mnesia Erlang term database.
Stars: ✭ 223 (-43.11%)
Mutual labels:  hex
serde-device-tree
Serialize & deserialize device tree binary using serde
Stars: ✭ 20 (-94.9%)
Mutual labels:  serde
Civitas
Civitas is an empire-building game written in Javascript with the help of the jQuery library.
Stars: ✭ 207 (-47.19%)
Mutual labels:  hex
stylelint-problem-matcher
A GitHub Action that registers a problem matcher for Stylelint's report format
Stars: ✭ 18 (-95.41%)
Mutual labels:  annotations
avro-serde-php
Avro Serialisation/Deserialisation (SerDe) library for PHP 7.3+ & 8.0 with a Symfony Serializer integration
Stars: ✭ 43 (-89.03%)
Mutual labels:  serde
Xprof
A visual tracer and profiler for Erlang and Elixir.
Stars: ✭ 246 (-37.24%)
Mutual labels:  hex

Custom de/serialization functions for Rust's serde

crates.io badge Build Status codecov CII Best Practices Rustexplorer


This crate provides custom de/serialization helpers to use in combination with serde's with-annotation and with the improved serde_as-annotation. Some common use cases are:

  • De/Serializing a type using the Display and FromStr traits, e.g., for u8, url::Url, or mime::Mime. Check DisplayFromStr for details.
  • Support for arrays larger than 32 elements or using const generics. With serde_as large arrays are supported, even if they are nested in other types. [bool; 64], Option<[u8; M]>, and Box<[[u8; 64]; N]> are all supported, as this examples shows.
  • Skip serializing all empty Option types with #[skip_serializing_none].
  • Apply a prefix to each field name of a struct, without changing the de/serialize implementations of the struct using with_prefix!.
  • Deserialize a comma separated list like #hash,#tags,#are,#great into a Vec<String>. Check the documentation for serde_with::StringWithSeparator::<CommaSeparator, T>.

Getting Help

Check out the user guide to find out more tips and tricks about this crate.

For further help using this crate you can open a new discussion or ask on users.rust-lang.org. For bugs, please open a new issue on GitHub.

Use serde_with in your Project

# Add the current version to your Cargo.toml
cargo add serde_with

The crate contains different features for integration with other common crates. Check the feature flags section for information about all available features.

Examples

Annotate your struct or enum to enable the custom de/serializer. The #[serde_as] attribute must be placed before the #[derive].

DisplayFromStr

Rustexplorer

#[serde_as]
#[derive(Deserialize, Serialize)]
struct Foo {
    // Serialize with Display, deserialize with FromStr
    #[serde_as(as = "DisplayFromStr")]
    bar: u8,
}

// This will serialize
Foo {bar: 12}

// into this JSON
{"bar": "12"}

Large and const-generic arrays

serde does not support arrays with more than 32 elements or using const-generics. The serde_as attribute allows circumventing this restriction, even for nested types and nested arrays.

On top of it, [u8; N] (aka, bytes) can use the specialized "Bytes" for efficiency much like the serde_bytes crate.

Rustexplorer

#[serde_as]
#[derive(Deserialize, Serialize)]
struct Arrays<const N: usize, const M: usize> {
    #[serde_as(as = "[_; N]")]
    constgeneric: [bool; N],

    #[serde_as(as = "Box<[[_; 64]; N]>")]
    nested: Box<[[u8; 64]; N]>,

    #[serde_as(as = "Option<[_; M]>")]
    optional: Option<[u8; M]>,

    #[serde_as(as = "Bytes")]
    bytes: [u8; M],
}

// This allows us to serialize a struct like this
let arrays: Arrays<100, 128> = Arrays {
    constgeneric: [true; 100],
    nested: Box::new([[111; 64]; 100]),
    optional: Some([222; 128]),
    bytes: [0x42; 128],
};
assert!(serde_json::to_string(&arrays).is_ok());

skip_serializing_none

This situation often occurs with JSON, but other formats also support optional fields. If many fields are optional, putting the annotations on the structs can become tedious. The #[skip_serializing_none] attribute must be placed before the #[derive].

Rustexplorer

#[skip_serializing_none]
#[derive(Deserialize, Serialize)]
struct Foo {
    a: Option<usize>,
    b: Option<usize>,
    c: Option<usize>,
    d: Option<usize>,
    e: Option<usize>,
    f: Option<usize>,
    g: Option<usize>,
}

// This will serialize
Foo {a: None, b: None, c: None, d: Some(4), e: None, f: None, g: Some(7)}

// into this JSON
{"d": 4, "g": 7}

Advanced serde_as usage

This example is mainly supposed to highlight the flexibility of the serde_as-annotation compared to serde's with-annotation. More details about serde_as can be found in the user guide.

#[serde_as]
#[derive(Deserialize, Serialize)]
enum Foo {
    Durations(
        // Serialize them into a list of number as seconds
        #[serde_as(as = "Vec<DurationSeconds>")]
        Vec<Duration>,
    ),
    Bytes {
        // We can treat a Vec like a map with duplicates.
        // JSON only allows string keys, so convert i32 to strings
        // The bytes will be hex encoded
        #[serde_as(as = "Map<DisplayFromStr, Hex>")]
        bytes: Vec<(i32, Vec<u8>)>,
    }
}

// This will serialize
Foo::Durations(
    vec![Duration::new(5, 0), Duration::new(3600, 0), Duration::new(0, 0)]
)
// into this JSON
{
    "Durations": [5, 3600, 0]
}

// and serializes
Foo::Bytes {
    bytes: vec![
        (1, vec![0, 1, 2]),
        (-100, vec![100, 200, 255]),
        (1, vec![0, 111, 222]),
    ],
}
// into this JSON
{
    "Bytes": {
        "bytes": {
            "1": "000102",
            "-100": "64c8ff",
            "1": "006fde"
        }
    }
}

License

Licensed under either of

at your option.

Contribution

For detailed contribution instructions please read CONTRIBUTING.md.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].